12

I am simply making a GET request to a Rest API using HttpURLConnection.

I need to add some custom headers but I am getting null while trying to retrieve their values.

Code:

URL url;
try {
    url = new URL("http://www.example.com/rest/");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // Set Headers
    conn.setRequestProperty("CustomHeader", "someValue");
    conn.setRequestProperty("accept", "application/json");

    // Output is null here <--------
    System.out.println(conn.getHeaderField("CustomHeader"));

    // Request not successful
    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException("Request Failed. HTTP Error Code: " + conn.getResponseCode());
    }

    // Read response
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer jsonString = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        jsonString.append(line);
    }
    br.close();
    conn.disconnect();
} catch (IOException e) {
    e.printStackTrace();
}

What am I missing?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46

2 Answers2

12

It is a good idea to send

conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("CustomHeader", token);

instead of

// Set Headers
conn.setRequestProperty("CustomHeader", "someValue");
conn.setRequestProperty("accept", "application/json");

Both the type value and header should be changed. it works in my case.

Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
  • 2
    It's a `GET` request. I am not sending any content & expecting the response of type `application/json` so, is there any reason for using `Content-Type` instead of `accept` here? – Abhishekh Gupta Oct 26 '16 at 06:26
  • Who took it upon themselves to rename "header" to "property" ? This was very surprising. – Wyck Sep 17 '20 at 20:12
7

The conn.getHeaderField("CustomHeader") returns the response header not the request one.

To return the request header use: conn.getRequestProperty("CustomHeader")

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115