我有
HttpResponse response = httpclient.execute(httpget);
我的方法可以通过设备和 PC 上的套接字传输 byte[],那么我如何将 HttpResponse 转换成 byte[] 然后再转换回 HttpResponse?
最佳答案
这并不容易。
如果你只是想要响应的主体,那么你可以这样做来获取它
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] bytes = baos.toByteArray();
然后您可以将内容添加到另一个 HttpResponse
对象,如下所示:
HttpResponse response = ...
response.setEntity(new ByteArrayEntity(bytes));
但这可能还不够好,因为您很可能需要原始响应中的所有其他内容;例如状态行和标题(包括原始内容类型和长度)。
如果你想处理整个响应,你似乎有两个选择:
您可以将响应分开(例如获取状态行、迭代 header )并手动序列化,然后在另一端执行相反的操作。
您可以使用
HttpResponseWriter
进行序列化,并使用HttpResponseParser
在另一端重建响应。这是解释here .
关于java - 将 HttpResponse 转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17741774/