额外的http标头不起作用

时间:2013-07-07 05:46:47

标签: java java-ee http-headers httpurlconnection httpconnection

我正在尝试在我的代码中将标题添加到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 个答案:

答案 0 :(得分:1)

getHeaderFields()返回在HTTP响应中发送的头字段,而不是HTTP请求中。您从未发送过这些标题:内容语言,转移编码等,但您可以在getHeaderFields()中获取它们。这是因为服务器发送了这些标头。 请求中设置的自定义标头字段可用于 http://localhost:8080/share/page

/ page可以使用以下方式访问这些标题字段:

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