java - 如何在java中发送http get请求并获取特定字段

标签 java json request http-get

在java中发送http get请求最简单的方法是什么,例如这个链接https://jsonplaceholder.typicode.com/todos/1 ,并且只取 ​​id 字段?

目前这是我正在使用的代码,但显然它以 json 格式打印所有内容

int responseCode = 0;
try {
    responseCode = httpClient.getResponseCode();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(
    new InputStreamReader(httpClient.getInputStream()))) {
    String line;

    while ((line = in.readLine()) != null) {
        response.append(line);
    }


} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

最佳答案

假设您在第三方库的使用方面不受限制,以下是您想要实现的目标的一个非常简单的示例。

为此,它使用 Apache 的 HTTPClient执行 GET 请求和 Jackson反序列化响应。

首先,您首先创建一个代表您预期响应对象的模型类:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Response {

    private Integer id;
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

}

请注意,该类用 @JsonIgnoreProperties(ignoreUnknown = true) 进行注释,它指示 Jackson 忽略任何无法映射到模型类的属性(即在我们的例子中,除了 >id 字段)。

有了这个,执行 GET 请求并检索响应的 id 字段就可以像下面的示例一样简单:

public class HttpClientExample {

    public static void main(String... args) {

        try (var client = HttpClients.createDefault()) {
            var getRequest = new HttpGet("https://jsonplaceholder.typicode.com/todos/1");
            getRequest.addHeader("accept", "application/json");

        HttpResponse response = client.execute(getRequest);
        if (isNot2xx(response.getStatusLine().getStatusCode())) {
            throw new IllegalArgumentException("Failed to get with code: " + response.getStatusLine().getStatusCode());
        }

        Response resp = new ObjectMapper().readValue(EntityUtils.toString(response.getEntity()), Response.class);
        System.out.println(resp.getId());

    } catch (IOException e) {
            e.printStackTrace();
    }

    }

    private static boolean isNot2xx(int statusCode) {
        return statusCode != 200;
    }

}

如上所述,此示例假设您可以使用第 3 方库。另请注意,如果您使用 Java 11,则可以省略使用 Apache 的 HTTP 客户端,因为新的 JDK 与 Java 自己的 HTTP 客户端捆绑在一起,该客户端提供了执行工作所需的所有功能。

关于java - 如何在java中发送http get请求并获取特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544112/

相关文章:

json - 让 jackson 忽略序列化为 json 时延迟初始化的字段

spring - 如何在 Spring webapp 中的 JSP 中获取正确的当前 URL

java - 如何在不遇到 SecurityException 的情况下从 Scala 脚本引用 java.sql?

java - 在 2 个 Bean 之间传递数据 JSF

java - 在运行时创建复合比较器以进行排序

javascript - AngularJS 根据日期检索 JSON 记录

node.js - 通过 NodeJS 将文件加载到 facebook Messenger 时出现问题

java - JodConverter 处理转换文档的多个请求

java - Apache Flink : aligning watermark among parallel tasks

java - 最终列表或数组不会存储值