httpclient 4如何获取字节

时间:2021-05-10 00:32:55
    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

这会将responseBody作为“字符串”,如何使用httpclient.execute(..)获取btye []?我想得到byte []的原因是因为我想写一些其他的输出流

3 个解决方案

#1


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

#2


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

您可以使用responseBody.getBytes()来获取byte []。

#3


Try HttpResponse.getEntity().writeTo(OutputStream)

#1


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

#2


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

您可以使用responseBody.getBytes()来获取byte []。

#3


Try HttpResponse.getEntity().writeTo(OutputStream)