6

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?

Olaf Kock
48.3k9 gold badges63 silver badges91 bronze badges
asked Jul 19, 2013 at 8:48

3 Answers 3

7

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.

answered Jul 19, 2013 at 9:51
Sign up to request clarification or add additional context in comments.

Comments

1

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();
}
answered Mar 9, 2021 at 20:22

Comments

0

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

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

answered Jul 19, 2013 at 8:51

1 Comment

Thank you with it i find good method (EntityUtils.toByteArray(entity)), but there is still problem to convert byte[] in HttpEntity.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.