chehom
chehom

Reputation: 63

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?

Upvotes: 6

Views: 33300

Answers (3)

Stephen C
Stephen C

Reputation: 718658

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();

Alternatively:

    byte[] bytes = EntityUtils.toByteArray(response.getEntity());

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.

Upvotes: 7

tostao
tostao

Reputation: 3048

With java11:

var client = HttpClient.newBuilder().build();
var request = HttpRequest.newBuilder()
            .uri(URI.create("https://yourdomain.test")).GET().build();
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (200 == response.statusCode()) {
            byte[] bytes = response.body();
}

Upvotes: 1

Ankit
Ankit

Reputation: 6622

you need to get it as a stream: response.getEntity().getContent()

then you can directly read the stream into a byte[].

Upvotes: 0

Related Questions