实现说明
HttpClient 同步请求与响应检查可以归结为类 SyncStatusCheck。
使用要点
- 直接运行文件,输出会带上标签,比如
status:、content-type:、body chars:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「HttpClient 同步请求与响应检查」会打印什么?
整个文件跑完,输出行以 status:、content-type:、body chars: 这类前缀开头。
核心语句
client.send(request, HttpResponse.BodyHandlers.ofString());
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();
代码示例
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class SyncStatusCheck {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.header("Accept", "text/html")
.GET()
.build();
// send() is the synchronous (blocking) call: it returns only with the response; see sendAsync for the chaining counterpart
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("status: " + response.statusCode());
System.out.println("content-type: "
+ response.headers().firstValue("content-type").orElse("n/a"));
System.out.println("body chars: " + response.body().length());
}
}