对于请求内容可以使用 BodyPublishers 封装的函数生成
HttpResponse 的API
对于响应的解析读取可以使用 BodyHandlers 或者 BodySubscribers 封装的函数处理
get 请求
HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/content/lwl"))
.GET()
.timeout(Duration.ofSeconds(10)) // 设置响应超时时间
.build();
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
post 请求
String data = .....// json 请求数据
HttpRequest request = HttpRequest.newBuilder(URI.create("https://www.baidu.com"))
.POST(HttpRequest.BodyPublishers.ofString(data, Charset.defaultCharset()))
.header("Content-Type", "application/json") //设置头部信息
.timeout(Duration.ofSeconds(10)) // 设置响应超时时间
.build();
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
欢迎指正文中错误
参考文章
HttpClient用法--这一篇全了解
HttpClient详细使用示例
Java9之HttpClientAPI实战详解
JDK 之 HttpClient(jdk11)