在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;
}
}
如上所述,此示例假定您可以使用第三方库。还要注意,如果您使用Java 11,则可以省略Apache的HTTP客户端,因为新的JDK与Java自己的HTTP客户端捆绑在一起,该HTTP客户端提供了执行工作所需的所有功能。