How can I read bytearray from HttpResponse?

I am making an http connection using the following code:

HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse response = client.execute(httpPost); 

I want to read bytearray from the response object.

How can I do it?

+4
source share
3 answers

You can read an array of bytes directly using the method: EntityUtils.toByteArray

Example

 HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("localhost:8080/myurl"); HttpResponse response = client.execute(get); byte[] content = EntityUtils.toByteArray(response.getEntity()); 
+5
source

You can use:

 HttpResponse response = client.execute(httpPost); String content = EntityUtils.toString(response.getEntity()); byte[] bytes = content.getBytes("UTF8"); 

You can replace the character encoding with one suitable for the answer.

+1
source

I did something very similar to this, but it was a long time ago.

Looking at my source code, I used

 HttpClient client = new DefaultHttpClient(); String url = "http://192.168.1.69:8888/sdroidmarshal"; HttpGet getRequest = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String proto = client.execute(getRequest, responseHandler); 

I am sure that ResponseHandler is the key to this. My get request just returned me something I needed as a string, which was pretty simple.

In the case of bytearray, you probably want to use an InputStream this way

 ResponseHandler<InputStream> responseHandler = new BasicResponseHandler(); InputStream in = client.execute(getRequest, responseHandler); 

After that, just handle the InputStream as usual.

A bit of a search engine suggested you also use HttpResponseHandler (), not BasicResponseHandler (), as in my example, I would creak.

The full source code of my work is here , it may be useful for you.

0
source

Source: https://habr.com/ru/post/1339973/


All Articles