Java 使用Apache HttpComponent no实体解析Http响应
我想用Java解析以下响应:Java 使用Apache HttpComponent no实体解析Http响应,java,http,apache-httpcomponents,Java,Http,Apache Httpcomponents,我想用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
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()
这是我从第4.1.3章学到的。但是,解析的HttpResponse具有空实体
事实上,无论我使用JSON内容、HTML内容,甚至Gzip,似乎都没有内容。怎么了?默认HTTPResponseParser只解析HTTP头,而不解析内容。该内容在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));