【问题标题】:Parsing Http Response with Apache HttpComponent no entity使用 Apache HttpComponent 无实体解析 Http 响应
【发布时间】:2015-10-22 11:25:27
【问题描述】:

我想用 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 压缩的内容),似乎都没有内容。怎么了?

【问题讨论】:

    标签: java http apache-httpcomponents


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-29
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      相关资源
      最近更新 更多