Convert HttpResponse to byte array
It is not easy.
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.toByteArray();
Then you could add the content to another HttpResponse
object as follows:
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.
You can use
HttpResponseWriter
to do the serializing andHttpResponseParser
to rebuild the response at the other end. This is explained here.
Admin
Updated on March 10, 2021Comments
-
Admin about 3 years
I have
HttpResponse response = httpclient.execute(httpget);
my method can transfer byte[] over sockets on device and PC, so how can i convert HttpResponse into byte[] and than back to HttpResponse?