Java
HttpURLConnection
Web Development
Programming
HTTP Headers

How to set a request header with Java HttpURLConnection

Codemia Knowledge Hub ·

Call setRequestProperty(name, value) on the HttpURLConnection before the request is sent, which means before connect(), getInputStream(), getOutputStream() or getResponseCode(). It replaces any previous value for that header name. Headers carry metadata such as authentication tokens, accepted response formats, content types, cache directives and custom application values.

Setting request headers

java
1import java.io.BufferedReader;
2import java.io.InputStreamReader;
3import java.net.HttpURLConnection;
4import java.net.URL;
5
6public class HeaderExample {
7    public static void main(String[] args) throws Exception {
8        URL url = new URL("https://httpbin.org/headers");
9        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
10
11        connection.setRequestMethod("GET");
12        connection.setConnectTimeout(5000);
13        connection.setReadTimeout(5000);
14        connection.setRequestProperty("Accept", "application/json");
15        connection.setRequestProperty("User-Agent", "Codemia-Demo/1.0");
16        connection.setRequestProperty("X-Request-ID", "demo-123");
17
18        int status = connection.getResponseCode();
19        System.out.println("HTTP status: " + status);
20
21        try (BufferedReader reader = new BufferedReader(
22                new InputStreamReader(connection.getInputStream()))) {
23            String line;
24            while ((line = reader.readLine()) != null) {
25                System.out.println(line);
26            }
27        }
28
29        connection.disconnect();
30    }
31}

All three headers are set before getResponseCode() triggers the network request.

setRequestProperty versus addRequestProperty

Use setRequestProperty when a header should have one final value. Use addRequestProperty when a header can appear more than once or you intentionally want several values.

java
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Accept", "text/plain");

setRequestProperty is the usual choice, since most application code treats a header as having one value.

Headers for POST requests

When you send a body, the server usually needs a matching Content-Type header to parse it:

java
1import java.io.OutputStream;
2import java.net.HttpURLConnection;
3import java.net.URL;
4import java.nio.charset.StandardCharsets;
5
6public class PostExample {
7    public static void main(String[] args) throws Exception {
8        URL url = new URL("https://httpbin.org/post");
9        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
10
11        connection.setRequestMethod("POST");
12        connection.setDoOutput(true);
13        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
14        connection.setRequestProperty("Authorization", "Bearer demo-token");
15
16        byte[] body = "\"hello\"".getBytes(StandardCharsets.UTF_8);
17        try (OutputStream out = connection.getOutputStream()) {
18            out.write(body);
19        }
20
21        System.out.println(connection.getResponseCode());
22        connection.disconnect();
23    }
24}

If the server expects JSON and the Content-Type is wrong or missing, you can get a 400 or 415 response even though the Java code compiled and ran.

Reading response headers

getHeaderField reads headers the server sent back, which is useful for rate limits, pagination, caching and redirects:

java
String contentType = connection.getHeaderField("Content-Type");
String retryAfter = connection.getHeaderField("Retry-After");

Request headers go from client to server; response headers come back from server to client. getHeaderField does not set outgoing values.

Commonly set request headers

  • Authorization for API tokens or basic auth
  • Accept for the preferred response format
  • Content-Type for the request body format
  • User-Agent for client identification
  • custom X-... or domain-specific headers for tracing and internal metadata

Header names are often standardized, but the required values depend on the API, so take them from its documentation.

Why a header seems to be ignored

  • It was set after the request started. Once the connection is established, setRequestProperty throws java.lang.IllegalStateException: Already connected instead of changing the request.
  • setDoOutput(true) was not called before writing a POST or PUT body. This is not a silent failure: getOutputStream() throws java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true).
  • The Content-Type does not match the body, so the server rejects or misreads it.
  • Missing timeouts and unread error streams make header problems look like hangs or empty responses.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design