java - 附加的 http header 不起作用

标签 java jakarta-ee http-headers httpurlconnection httpconnection

我正在尝试将 header 添加到 http 中并在我的代码中添加 header -

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

但是当我尝试打印这些 header 的值时,它会显示为空。请让我知道如何获取 header 值。我得到的输出

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

最佳答案

getHeaderFields() 返回在 HTTP 响应中发送的 header 字段,而不是在 HTTP 请求中发送的 header 字段。您从未发送过这些 header :Content-Language、Transfer-Encoding 等,但您在 getHeaderFields() 中获取了它们。这是因为服务器发送了这些 header 。 请求中设置的自定义 header 字段将可用于 http://localhost:8080/share/page

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

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

关于java - 附加的 http header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17509632/

相关文章:

safari - 在 Safari 中查看 HTTP header

java - 迭代时出现 NoSuchElementException

java - 对一对多关系对象的引用不会更新

java - Java EE 应用程序中的 System.out.println 危害

java - 制作网络服务,采用哪种方法?

REST 的 HTTP 修改动词?

angular - 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 Access-Control-Allow-Methods

java - 无法将按键发送到输入元素

java - Miglayout + hidemode 3 = 显示控件时不需要的自动滚动

java - OpenGL 淡出/淡入不起作用