gpt4 book ai didi

java - 使用 Apache HttpComponent 解析 Http 响应没有实体

转载 作者:可可西里 更新时间:2023-11-01 16:28:14 25 4
gpt4 key购买 nike

我想用 Java 解析以下响应:

HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
ETag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 138
Accept-Ranges: bytes
Connection: close

<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>

使用 Apache HttpComponent httpcore-4.4.3

所以我的代码看起来像:

  String response = "HTTP/1.1 200 OK\r\n" +
"Date: Mon, 23 May 2005 22:38:34 GMT\r\n" +
"Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)\r\n" +
"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT\r\n" +
"ETag: \"3f80f-1b6-3e1cb03b\"\r\n" +
"Content-Type: text/html; charset=UTF-8\r\n" +
"Content-Length: 138\r\n" +
"Accept-Ranges: bytes\r\n" +
"Connection: close\r\n" +
"\r\n" +
"<html\n" +
"<head>\n" +
" <title>An Example Page</title>\n" +
"</head>\n" +
"<body>\n" +
" Hello World, this is a very simple HTML document.\n" +
"</body>\n" +
"</html>";

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(response.getBytes("UTF-8"));

HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
SessionInputBufferImpl inbuffer = new SessionInputBufferImpl(metrics, 8 * 1024);
inbuffer.bind(byteArrayInputStream);

HttpResponse httpResponse = new DefaultHttpResponseParser(inbuffer).parse();
httpResponse.getEntity()

我从 http://hc.apache.org/httpcomponents-core-ga/tutorial/html/advanced.html 中获取的第 4.1.3 章。然而,已解析的 HttpResponse 具有空实体

实际上无论我使用什么响应(JSON 内容、HTML 内容,甚至 gzip 压缩),似乎都没有内容。怎么了?

最佳答案

DefaultHttpResponseParser 只解析 HTTP header ,不解析内容。 SessionInputBufferImpl 中的内容仍然可用。要检索它,您可以使用以下代码(例如):

ContentType contentType = null;
Header contentTypeHeader = httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE);
if (contentTypeHeader != null) {
contentType = ContentType.parse(contentTypeHeader.getValue());
}
byte[] content = new byte[inbuffer.length()]; // length is what's left in the buffer
inbuffer.read(content);
httpResponse.setEntity(new ByteArrayEntity(content, contentType));

关于java - 使用 Apache HttpComponent 解析 Http 响应没有实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33279882/

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