How do I set and read custom HTTP Headers using HttpURLConnection in Java?

To set and read custom HTTP headers using HttpURLConnection in Java, you can make use of its methods setRequestProperty to set headers and getHeaderField to read them.

Here’s how you can do it:

Setting Custom HTTP Headers

You can set custom HTTP headers on a request using the setRequestProperty method. For example:

package org.kodejava.net;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpHeadersExample {
   public static void main(String[] args) {
      try {
         URL url = new URL("https://example.com/api");
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();

         // Set HTTP method (GET, POST, etc.)
         connection.setRequestMethod("GET");

         // Set custom HTTP headers
         connection.setRequestProperty("Custom-Header", "HeaderValue");
         connection.setRequestProperty("User-Agent", "MyCustomAgent");

         // Optional: Add request body (for POST or PUT)
         connection.setDoOutput(true);
         try (OutputStream os = connection.getOutputStream()) {
            os.write("Request Body".getBytes());
            os.flush();
         }

         int responseCode = connection.getResponseCode();
         System.out.println("Response Code: " + responseCode);

         // Close the connection
         connection.disconnect();

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Reading Response Headers

You can read response headers using the getHeaderField and getHeaderFieldKey methods.

package org.kodejava.net;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class ReadHttpHeadersExample {
   public static void main(String[] args) {
      try {
         URL url = new URL("https://example.com/api");
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("GET");

         // Read all headers
         System.out.println("Headers:");
         for (int i = 0;; i++) {
            String headerKey = connection.getHeaderFieldKey(i);
            String headerValue = connection.getHeaderField(i);

            if (headerKey == null && headerValue == null) {
               break; // No more headers
            }
            System.out.println(headerKey + ": " + headerValue);
         }

         connection.disconnect();

      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Explanation

  1. Setting Headers
    • Use setRequestProperty(String key, String value) to set a custom header.
    • For example, connection.setRequestProperty("Authorization", "Bearer token") for setting an Authorization header.
  2. Sending a Request Body
    • If you want to send a POST or PUT request with custom headers, you need to write a body to the request through the OutputStream.
  3. Reading Headers
    • Use getHeaderFieldKey(int) to retrieve the header key and getHeaderField(int) to get its value.
    • You can loop through headers until both the key and value are null, indicating no more headers.
  4. Common Use-Cases
    • Assigning client information via User-Agent.
    • Sending authentication tokens via Authorization.
    • Using custom headers like X-Custom-Header.

Example Output for Reading Headers:

When you print headers, you may see something like:

Headers:
null: HTTP/1.1 200 OK
Date: Mon, 23 Oct 2023 10:30:00 GMT
Content-Type: application/json
Content-Length: 123
Server: Apache

This shows both standard headers and any custom headers returned by the server.

By combining the above methods, you can handle both setting and reading custom HTTP headers programmatically in Java using HttpURLConnection.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.