How to convert HttpResponse to String in Java

Following code snippet explains how to convert HttpResponse object to String in Java

Steps

  1. Call httpclient.execute()
  2. Get the InputStream from the response
  3. Convert the InputStream to ByteArrayOutputStream
  4. Convert the ByteArrayOutputStream to String
  5. Close the request and InputStream


private String executeAndGetResponse(HttpRequestBase request)
      throws IOException, ClientProtocolException, Exception, UnsupportedEncodingException {
    HttpResponse response = httpClient.execute(request);
    InputStream inputStream = response.getEntity().getContent();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
      result.write(buffer, 0, length);
    }
    String strRes = result.toString(StandardCharsets.UTF_8.name());
   
    request.releaseConnection();
    inputStream.close();
    return strRes;
  }

Comments

Popular posts from this blog

Difference between volatile and synchronized

Converting Java Map to String

Masking Credit Card number in Java