在 Java 中,是否可以在 HttpURLConnection 上查看多个具有相同名称的响应 header ?
在 Oracle documentation for "GetHeaderField" ,它指出:
If called on a connection that sets the same header multiple times with possibly different values, only the last value is returned.
我的问题是,如何查看多次设置的 header 的所有不同值?
最佳答案
List<String> values = conn.getHeaderFields().get("X-Header-Of-Interest");
完整示例
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnectionTest {
public static void main (String[] args) throws IOException {
URL url = new URL("http://localhost:8888/");
URLConnection conn = url.openConnection();
conn.getContent(); // Force request
System.out.println(conn.getHeaderFields().get("X-Funky-Header"));
}
}
在 Linux 上,您可以使用 netcat 创建一个简单的单请求服务器进行测试
$ echo -e 'HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nX-Funky-Header: value1\r\nX-Funky-Header: value2\r\n\r\nContent' | nc -l 8888 &
关于java - Java中同名的多个响应头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22390603/