How can I read a bytearray from an HttpResponse?
I'm making an http connection 开发者_开发百科using following code:
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = client.execute(httpPost);
I want to read a bytearray from the response object.
How would I do that?
You can read the byte array directly with 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());
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 appropriate for the response.
I did something very similar to this, but it was a while 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'm pretty certain that the ResponseHandler is the key to this. My get request simply returned something I needed as a string, which was quite simple.
In the case of a bytearray you'll probably want to use an InputStream like so
ResponseHandler<InputStream> responseHandler = new BasicResponseHandler();
InputStream in = client.execute(getRequest, responseHandler);
After which just handle the InputStream as normal.
A bit of googling suggested you may also need to use HttpResponseHandler() rather than BasicResponseHandler() as in my example, I'd fiddle.
The full source code of my work is here, it might be helpful for you.
Kotlin Way
run this on async task on background thread otherwise it will through the error that network task is running on main thread
doAsync {
val client: HttpClient = DefaultHttpClient()
val get = HttpPost("*your url*")
get.setHeader("Authorization","Bearer "+Utils.token)
val response: HttpResponse = client.execute(get)
val content = EntityUtils.toByteArray(response.getEntity())
onComplete {
createPdf(content)
}
}
精彩评论