Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the http response as a Json Object in Java

I want to send a HTTP request using CloseableHttpClient and then capture the body of the response in a JSON object so I can access the key values like this: responseJson.name etc

I can capture the response body as a string ok using the code below but how can I capture it as a JSON object?

CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder();

    builder.setScheme("https").setHost("login.xxxxxx").setPath("/x/oauth2/token");
    URI uri = builder.build();
    HttpPost request = new HttpPost(uri);
    HttpEntity entity = MultipartEntityBuilder.create()
            .addPart("grant_type", grantType)
            .build();
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);
    assertEquals(200, response.getStatusLine().getStatusCode());

    //This captures and prints the response as a string
    HttpEntity responseBodyentity = response.getEntity();
    String responseBodyString = EntityUtils.toString(responseBodyentity);
    System.out.println(responseBodyString);
like image 796
Matt Avatar asked Oct 25 '25 04:10

Matt


1 Answers

you can type cast your response string to JSON Object.

String to JSON using Jackson with com.fasterxml.jackson.databind:

Assuming your json-string represents as this: jsonString = "{"name":"sample"}"

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBodyString);
String phoneType = node.get("name").asText();

Using org.json library:

JSONObject jsonObj = new JSONObject(responseBodyString);
String name = jsonObj.get("name");
like image 142
Sree Avatar answered Oct 26 '25 18:10

Sree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!