Posts

Showing posts from September, 2019

How to convert HttpResponse to String in Java

Following code snippet explains how to convert HttpResponse object to String in Java 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; }

Jackson Object Mapper to conver String to JsonNode

Following are some of the code snippet for Jackson Object Mapper Convert String to JsonNode Object String data; JsonNode jsonNode = getObjectMapper().readTree(data); Convert an Object to JSON String String jsonString = getObjectMapper().writeValueAsString(object); Convert InputStream to JsonNode Object InputStream inputStream; JsonNode jsonNode = getObjectMapper().readTree(inputStream);