假设您对第三方库的使用没有限制,下面是一个非常简单的例子,说明您想要实现什么。
首先,创建一个表示预期响应对象的模型类:
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忽略任何不能映射到model类的属性(即在我们的例子中,除了
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;
}
}
如上所述,此示例假设您可以使用第三方库。还要注意,如果您使用Java 11,您可以省略使用Apache中的HTTP客户端,因为新的JDK与Java自己的HTTP客户端捆绑在一起,后者提供执行工作所需的所有功能。