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

Mat*_*att 3 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");
Run Code Online (Sandbox Code Playgroud)
    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);
Run Code Online (Sandbox Code Playgroud)

Sre*_*ree 6

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

使用Jacksonwith将字符串转换为 JSONcom.fasterxml.jackson.databind

假设您的 json 字符串表示如下: 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();
Run Code Online (Sandbox Code Playgroud)

使用org.json库:

JSONObject jsonObj = new JSONObject(responseBodyString);
String name = jsonObj.get("name");
Run Code Online (Sandbox Code Playgroud)