Java
HttpURLConnection
Web Development
Programming
HTTP Headers

Adding header for HttpURLConnection

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

When you use HttpURLConnection, headers are how you tell the server what you want and who you are. They carry metadata such as authentication tokens, accepted response formats, content types, cache directives, and custom application values.

The important detail is timing. Request headers must be set before the request is sent, which usually means before calling getInputStream(), getOutputStream(), or connect().

Setting Request Headers

The main API is setRequestProperty(key, value). It replaces any previous value for that header name.

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}

This example sets three headers before triggering the network request with getResponseCode().

setRequestProperty Versus addRequestProperty

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

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

In practice, setRequestProperty is the common choice. It matches how most application code thinks about headers.

Adding Headers for POST Requests

Headers matter even more when sending a request body. A server often expects a matching Content-Type header so it can parse the body correctly.

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, sending a body without the correct Content-Type can produce a 400 or 415 response even though the Java code compiled and ran.

Reading Response Headers Too

HttpURLConnection can also read response headers. That is useful for rate-limit tracking, pagination, caching, and redirect logic.

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. Keeping that direction clear prevents a lot of confusion when debugging.

Common Header Use Cases

Some of the most common request headers are:

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

Use exact header values from the server or API documentation. Header names are standardized in many cases, but the required values are application-specific.

Common Pitfalls

  • Setting headers after the request has already started. Once the connection is established, later header changes may be ignored.
  • Forgetting setDoOutput(true) before writing a request body on POST or PUT requests.
  • Mixing request headers and response headers conceptually. getHeaderField reads the response; it does not set outgoing values.
  • Using the wrong Content-Type, which causes the server to reject or misinterpret the body.
  • Ignoring timeouts and error streams, making header-related failures look like hangs or empty responses.

Summary

  • Use setRequestProperty to add or replace an outgoing HTTP header.
  • Set headers before sending the request.
  • For body-based requests, make Content-Type match the payload format.
  • 'addRequestProperty is only needed when multiple values are intentional.'
  • Good header handling usually depends more on order and correctness than on API complexity.

Course illustration
Course illustration

All Rights Reserved.