Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HttpResponse to byte array

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?

like image 586
chehom Avatar asked Jul 19 '13 08:07

chehom


1 Answers

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 and HttpResponseParser to rebuild the response at the other end. This is explained here.

like image 125
Stephen C Avatar answered Sep 29 '22 19:09

Stephen C