How to convert HttpResponse to String in Java
Following code snippet explains how to convert HttpResponse object to String in Java
Steps
Steps
- Call httpclient.execute()
- Get the InputStream from the response
- Convert the InputStream to ByteArrayOutputStream
- Convert the ByteArrayOutputStream to String
- 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
Post a Comment