如何在Java中将http响应捕获为Json对象

时间:2019-03-06 17:00:44

标签: java json apache-httpclient-4.x

我想使用CloseableHttpClient发送一个HTTP请求,然后在JSON对象中捕获响应的主体,这样我就可以像这样访问键值:responseJson.name等

我可以使用以下代码将响应主体捕获为字符串确定,但是如何将其捕获为JSON对象?

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);

3 个答案:

答案 0 :(得分:2)

您可以键入将响应字符串转换为JSON对象。

使用Jacksoncom.fasterxml.jackson.databind的JSON字符串

假设您的json-string表示为: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();

使用org.json库:

JSONObject jsonObj = new JSONObject(responseBodyString);
String name = jsonObj.get("name");

答案 1 :(得分:0)

只需将字符串转换为JSONObject,然后获取name的值

JSONObject obj = new JSONObject(responseBodyString);
System.out.println(obj.get("name"));

答案 2 :(得分:0)

我的建议是,由于您已经将JSON作为字符串,请编写一种使用google'Splitter'对象并定义要拆分为K-V对的字符的方法。

例如,我对K-V对所做的操作与从Spring Boot应用程序得到的字符串相同,并根据特殊的','字符进行分割:

private Map<String, String> splitToMap(String in) {

    return Splitter.on(", ").withKeyValueSeparator("=").split(in);
}

用例如“:”替换,这应该将您的JSON字符串作为K-V对。

下面的分割器Mvn依赖项:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>21.0</version>
</dependency>

希望这可以帮助您开始。