将 HttpResponse 转换为字节数组

che*_*hom 5 java sockets apache http

我有

 HttpResponse response = httpclient.execute(httpget);
Run Code Online (Sandbox Code Playgroud)

我的方法可以通过设备和 PC 上的套接字传输 byte[],那么我如何将 HttpResponse 转换为 byte[],然后再转换回 HttpResponse?

Ste*_*n C 5

这不简单。

如果你只是想要响应的正文,那么你可以这样做来抓住它

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    response.getEntity().writeTo(baos);
    byte[] bytes = baos.toByteArray();
Run Code Online (Sandbox Code Playgroud)

然后您可以将内容添加到另一个HttpResponse对象,如下所示:

    HttpResponse response = ...
    response.setEntity(new ByteArrayEntity(bytes));
Run Code Online (Sandbox Code Playgroud)

但这可能还不够好,因为您很可能需要原始响应中的所有其他内容;例如状态行和标题(包括原始内容类型和长度)。

如果您想处理整个响应,您似乎有两种选择:

  • 您可以将响应分开(例如获取状态行,迭代标题)并手动序列化,然后在另一端执行相反的操作。

  • 您可以使用HttpResponseWriter来进行序列化并HttpResponseParser在另一端重建响应。这是解释here