获取原始HTTP响应标头

p45*_*53d 10 java header http

有没有办法获得原始响应http标头?

getHeaderField()方法对我不起作用,因为服务器吐出多个"Set-Cookie",其中一些会丢失.

Bal*_*usC 34

getHeaderField()方法对我不起作用

你在上下文中问这个java.net.URLConnection,是吗?不可以,无法获取原始HTTP响应头URLconnection.你需要回到低级别的Socket编程.这是一个SSCCE,只是复制'n'paste'n'run它.

package com.stackoverflow.q2307291;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class Test {

    public static void main(String[] args) throws IOException {
        String hostname = "stackoverflow.com";
        int port = 80;

        Socket socket = null;
        PrintWriter writer = null;
        BufferedReader reader = null;

        try {
            socket = new Socket(hostname, port);
            writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            writer.println("GET / HTTP/1.1");
            writer.println("Host: " + hostname);
            writer.println("Accept: */*");
            writer.println("User-Agent: Java"); // Be honest.
            writer.println(""); // Important, else the server will expect that there's more into the request.
            writer.flush();

            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            for (String line; (line = reader.readLine()) != null;) {
                if (line.isEmpty()) break; // Stop when headers are completed. We're not interested in all the HTML.
                System.out.println(line);
            }
        } finally {
            if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
            if (writer != null) { writer.close(); }
            if (socket != null) try { socket.close(); } catch (IOException logOrIgnore) {} 
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

为了避免每个人都尝试这个片段而导致SO过载,这里是输出的样子:

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Expires: Sun, 21 Feb 2010 20:39:08 GMT
Server: Microsoft-IIS/7.5
Date: Sun, 21 Feb 2010 20:39:07 GMT
Connection: close
Content-Length: 208969

要了解有关以低级方式发送HTTP请求的更多信息,请阅读HTTP规范.

但是,您可能希望使用getHeaderFields()方法来检索具有多个值的标头.该getHeaderField()即只返回最后一个值,按照链接的API文档.

List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
Run Code Online (Sandbox Code Playgroud)


ost*_*ard 6

不完全'原始'但简洁:

for (Map.Entry<String, List<String>> k : myHttpURLConnection.getHeaderFields().entrySet()) {
    System.out.println(k.toString());
}
Run Code Online (Sandbox Code Playgroud)

如果您担心某些标题丢失,请使用:

for (Map.Entry<String, List<String>> k : myHttpURLConnection.getHeaderFields().entrySet()) {
    for (String v : k.getValue()){
         System.out.println(k.getKey() + ":" + v);
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:迟到总比没有好.:)

  • @ p4553d - 这就是为什么entrySet返回一个List <String>作为值......我想. (2认同)