获取原始 HTTP 响应标头

时间:2023-04-19
本文介绍了获取原始 HTTP 响应标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

解决方案

getHeaderField() 方法对我不起作用

您是在 <代码>java.net.URLConnection,是吗?不,使用 URLconnection 无法获取原始 HTTP 响应标头.您需要退回到低级别的 Socket 编程.这是一个SSCCE,只需复制'n'paste'n'运行它.

包com.stackoverflow.q2307291;导入 java.io.BufferedReader;导入 java.io.IOException;导入 java.io.InputStreamReader;导入 java.io.OutputStreamWriter;导入 java.io.PrintWriter;导入 java.net.Socket;公共类测试{公共静态 void main(String[] args) 抛出 IOException {字符串主机名 = stackoverflow.com";国际端口 = 80;套接字套接字 = null;PrintWriter 作家 = null;BufferedReader 阅读器 = null;尝试 {套接字 = 新套接字(主机名,端口);writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));writer.println("GET/HTTP/1.1");writer.println("主机:" + 主机名);writer.println("接受:*/*");writer.println("用户代理:Java");//说实话.writer.println("");//重要,否则服务器会期望请求中包含更多内容.writer.flush();reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));for (String line; (line = reader.readLine()) != null;) {if (line.isEmpty()) 中断;//当标题完成时停止.我们对所有的 HTML 不感兴趣.System.out.println(line);}} 最后 {if (reader != null) try { reader.close();} 捕捉(IOException logOrIgnore){}if (writer != null) { writer.close();}if (socket != null) try { socket.close();} 捕捉(IOException logOrIgnore){}}}}

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

<上一页>HTTP/1.1 200 正常缓存控制:私有内容类型:文本/html;字符集=utf-8过期:2010 年 2 月 21 日星期日 20:39:08 GMT服务器:Microsoft-IIS/7.5日期:2010 年 2 月 21 日星期日 20:39:07 GMT连接:关闭内容长度:208969

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

但是,您可能想使用 getHeaderFields() 方法来检索具有多个值的标头.<代码>getHeaderField() 即只返回最后一个值,根据链接的 API 文档.

列表<字符串>cookies = connection.getHeaderFields().get("Set-Cookie");

Is there any way to get raw response http header?

The getHeaderField() method doesn't work for me, because server spits multiple 'Set-Cookie' and some of them get lost.

解决方案

The getHeaderField() method doesn't work for me

You're asking this in the context of java.net.URLConnection, is it? No, obtaining the raw HTTP response headers is not possible with URLconnection. You'll need to fall back to low-level Socket programming. Here's an SSCCE, just copy'n'paste'n'run it.

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

}

To avoid SO being overloaded by everyone trying this snippet, here's how the output will look like:

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

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

这篇关于获取原始 HTTP 响应标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:尝试使用正确的行标题创建 JTable 下一篇:如何覆盖 http-header “主机"在 HttpURLConnection

相关文章

最新文章