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

时间:2015-10-22 11:25:28

标签: 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-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有 null entity

实际上,无论我使用什么样的响应(内容包含JSON,HTML内容,甚至是gzip),似乎都没有内容。有什么问题?

1 个答案:

答案 0 :(得分:4)

DefaultHttpResponseParser仅解析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));