转换的Htt presponse到字节数组 [英] Convert HttpResponse to byte array
问题描述
我
HttpResponse response = httpclient.execute(httpget);
我的方法可以传输的字节[]在对设备和PC插槽,所以,我怎么可以转换的Htt presponse成字节[]和不是回来了Htt presponse?
my method can transfer byte[] over sockets on device and PC, so how can i convert HttpResponse into byte[] and than back to HttpResponse?
推荐答案
这是不容易的。
如果您只是想回应的身体,那么你可以做到这一点抓住它。
If you simply wanted the body of the response, then you could do this to grab it
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] bytes = baos.getBytes();
然后,你可以添加内容到另一个的Htt presponse
对象如下:
HttpResponse response = ...
response.setEntity(new ByteArrayEntity(bytes));
但是,这可能还不够好,因为你很可能需要所有的原始响应其他的东西;例如状态行和头文件(包括原始内容类型和长度)。
But that's probably not good enough because you most likely need all of the other stuff in the original response; e.g. the status line and the headers (including the original content type and length).
如果您要处理整个响应,你似乎有两种选择:
If you want to deal with the whole response, you appear to have two choices:
-
您可以挑选响应分开(例如获取状态行,遍历头)和手动序列化,然后做相反的另一端。
You could pick the response apart (e.g. getting the status line, iterating the headers) and manually serialize, then do the reverse at the other end.
您可以使用的Htt presponseWriter
做序列化和的Htt presponseParser
重建在另一端的响应。这是解释这里。
You can use HttpResponseWriter
to do the serializing and HttpResponseParser
to rebuild the response at the other end. This is explained here.
这篇关于转换的Htt presponse到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!