2013-07-07 26 views
0

我试图头添加到HTTP和低于我的代码 -额外的HTTP标头不工作

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")); 

但是,当我试图打印的头,然后它是未来为空值。请让我知道如何获取标题值。输出我得到

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 

回答

1

getHeaderFields()返回头中的HTTP响应进行发送的,而不是在HTTP请求中的字段。你从来没有发送过这些头文件:Content-Language,Transfer-Encoding等,但你可以在getHeaderFields()中获得它们。这是因为服务器发送了这些标头。 在请求设置的自定义首部字段将提供给http://localhost:8080/share/page

/页可使用访问这些报头字段:

request.getHeader("SsoUserHeader"); //admin 
request.getHeader("mysso"); //hi 
request.getHeader("Authorization");