Question

I'm trying to add headers into http and below in my code -

URL url = new URL("http://localhost:8080/share/page"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("SsoUserHeader", "admin"); 
conn.addRequestProperty("mysso", "hi");
conn.setRequestProperty("Authorization",basicAuth );
conn.connect();

Map<String, List<String>> hdrs = conn.getHeaderFields();
Set<String> hdrKeys = hdrs.keySet();
for (String k : hdrKeys)
    System.out.println("Key: " + k + "  Value: " + hdrs.get(k));

System.out.println("Header1: "+conn.getHeaderField("SsoUserHeader"));
System.out.println("Header2: "+conn.getHeaderField("mysso"));
System.out.println("Header3: "+conn.getHeaderField("Authorization"));

But when I'm trying to print the values of those headers then it is coming as null. Please let me know how to get the header value. Output I'm getting

Key: null  Value: [HTTP/1.1 200 OK]
Key: Content-Language  Value: [en-US]
Key: Transfer-Encoding  Value: [chunked]
Key: Date  Value: [Sun, 07 Jul 2013 05:30:45 GMT]
Key: Set-Cookie  Value: [JSESSIONID=E6BCB7632619ABF41D1A7C6D7CDC53E4;  
                                Path=/share/; HttpOnly]

Key: Content-Type  Value: [text/html;charset=utf-8]
Key: Server  Value: [Apache-Coyote/1.1]
Key: Cache-Control  Value: [no-cache]

Header1: null
Header2: null
Header3: null
Était-ce utile?

La solution

getHeaderFields() returns header fields that were sent in the HTTP response, not in the HTTP request. You never sent these headers: Content-Language, Transfer-Encoding, etc. and yet you get them in getHeaderFields(). This is because the server sent these headers. The custom header fields set in the request will be available to http://localhost:8080/share/page

/page can access these header fields using:

request.getHeader("SsoUserHeader"); //admin
request.getHeader("mysso"); //hi
request.getHeader("Authorization"); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top