Configuring a custom header using HttpURLConnection

I am new to Java and I just make a GET request to the Rest API using HttpURLConnection .

I need to add some custom headers, but I get null trying to get their values.

The 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? Any suggestions.

+6
source share
2 answers

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

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

+4
source

It is a good idea to send

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

instead

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

Both the type value and the title must be changed. It works in my case.

+4
source

All Articles