2
    HttpGet httpget = new HttpGet("http://www.google.com/"); 

    System.out.println("executing request " + httpget.getURI());

    // Create a response handler
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = httpclient.execute(httpget, responseHandler);  

this will get responseBody as "string" , how to get btye[] with httpclient.execute(..) ? the reason i want to get byte[] is because i want to write to some other outputstream

cometta
  • 35,071
  • 77
  • 215
  • 324

3 Answers3

4
public byte[] executeBinary(URI uri) throws IOException, ClientProtocolException {
    HttpGet httpget = new HttpGet(uri);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    entity.writeTo(baos);
    return baos.toByteArray();
}
Alex R
  • 11,364
  • 15
  • 100
  • 180
  • Is it fine to leave baos not closed over here, or we need to explicitly close it by baos.close() ? – insanely_sin Mar 28 '17 at 18:20
  • 1
    @AbhishekSen no, see https://stackoverflow.com/questions/2330569/closing-a-bytearrayoutputstream-has-no-effect – Alex R Dec 11 '17 at 18:13
0

You can use the responseBody.getBytes() to get byte[].

Carlos
  • 1,696
  • 1
  • 14
  • 21
0

Try HttpResponse.getEntity().writeTo(OutputStream)

Triguna
  • 107
  • 1
  • 1