gpt4 book ai didi

java - 获取原始 HTTP 响应 header

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:28 24 4
gpt4 key购买 nike

有什么方法可以获取原始响应 http header 吗?

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

最佳答案

The getHeaderField() method doesn't work for me

您是在 java.net.URLConnection 的上下文中问这个问题的, 是吗?不,使用 URLconnection 无法获取原始 HTTP 响应 header 。你需要回退到低级别 Socket编程。这是一个 SSCCE ,只需复制'n'粘贴'然后运行它。

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) {}
}
}

}

为了避免 SO 被尝试此代码段的每个人过载,输出如下所示:

HTTP/1.1 200 OKCache-Control: privateContent-Type: text/html; charset=utf-8Expires: Sun, 21 Feb 2010 20:39:08 GMTServer: Microsoft-IIS/7.5Date: Sun, 21 Feb 2010 20:39:07 GMTConnection: closeContent-Length: 208969

To learn more about sending HTTP requests the low-level way, read the HTTP specification.

However, you probably want to make use of getHeaderFields() method instead to retrieve a header with multiple values. The getHeaderField() namely only returns the last value, as per the linked API doc.

List<String> cookies = connection.getHeaderFields().get("Set-Cookie");

关于java - 获取原始 HTTP 响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2307291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com