【问题标题】:how to send http get requests in java and take a specific field如何在java中发送http get请求并获取特定字段
【发布时间】:2020-04-19 23:36:19
【问题描述】:

在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();
}

【问题讨论】:

    标签: java json request http-get


    【解决方案1】:

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

    为此,它使用 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;
        }
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多