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);
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");
Just convert the string into JSONObject
then get the value for name
JSONObject obj = new JSONObject(responseBodyString);
System.out.println(obj.get("name"));
What I would recommend is since you already have your JSON as a string, write a method which makes use of the google 'Splitter' object and define the characters on which you want to split into KV pairs.
For example I did the same for KV pairs as a string coming from a Spring Boot app and split based on the special ',' characters:
private Map<String, String> splitToMap(String in) {
return Splitter.on(", ").withKeyValueSeparator("=").split(in);
}
replace with for example ": " and this should pick up your JSON string as KV pairs.
Splitter Mvn dependency below:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
hope this helps you make a start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.