jdk11 httpclient的基本使用
httpclient构建请求参数java.net.http.HttpRequest
- 请求 URI
- 请求类型(GET、PUT、POST、DELETE)
- 请求体
- 超时时间
- 请求请求头
HttpRequest request = HttpRequest.newBuilder()
// 请求url
.uri(URI.create("http://openjdk.java.net/"))
// 超时时间
.timeout(Duration.ofMinutes(1))
// 请求头
.header("Content-Type", "application/json")
// 请求类型GET、POST、PUT、DELETE
.POST(HttpRequest.BodyPublishers.ofString("请求体"))
.build();
发送请求java.net.http.HttpClient
- 首选协议版本( HTTP/1.1 或 HTTP/2 )
- 是否跟随重定向
- 代理
- 身份验证器
HttpClient client = HttpClient.newBuilder()
// 首选协议版本 默认情况下,客户端将使用 HTTP/2发送请求。发送到尚不支持 HTTP/2的服务器的请求将自动降级为HTTP/1.1。
.version(HttpClient.Version.HTTP_2)
// 重定向策略
.followRedirects(HttpClient.Redirect.NORMAL)
// 代理
.proxy(ProxySelector.of(new InetSocketAddress("www-proxy.com", 8080)))
// 超时时间
.connectTimeout(Duration.ofSeconds(6))
.build();
try {
// 发送同步请求
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
// 发送异步请求
var future = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
var responseAsync = future.get();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
直接使用默认设置发送请求
// 也可以直接使用默认设置发送请求
HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
请求体HttpRequest.BodyPublishers
/**
* json 类型
*/
HttpRequest.BodyPublishers.ofString("{\"json\":\"json\"}");
/**
* InputStream
*/
HttpRequest.BodyPublishers.ofInputStream(()
-> {
try {
return new FileInputStream("json.txt");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
});
/**
* 字节数组
*/
try {
HttpRequest.BodyPublishers.ofByteArray(
Files.readAllBytes(Path.of("json.byte")));
} catch (IOException e) {
throw new RuntimeException(e);
}
/**
* file文件
*/
try {
HttpRequest.BodyPublishers.ofFile(Path.of("json.txt"));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
/**
* 不需要请求体
*/
HttpRequest.BodyPublishers.noBody();
/**
* jdk16 新增
* 将多个BodyPublisher顺序拼接
*/
HttpRequest.BodyPublishers.concat(
HttpRequest.BodyPublishers.ofString("{\"json\":\"json\"}"),
HttpRequest.BodyPublishers.ofString("{\"json2\":\"json2\"}"));
HttpRequest.BodyPublishers.fromPublisher();
响应头HttpResponse.BodyHandlers
// 丢弃响应体积
HttpResponse.BodyHandlers.discarding();
// 丢弃响应体,返回给定的替换值
HttpResponse.BodyHandlers.replacing("自定义替换值");
// 返回byte数组
HttpResponse.BodyHandlers.ofByteArray();
// 返回string
HttpResponse.BodyHandlers.ofString();
// 下载文件并返回路径
HttpResponse.BodyHandlers.ofFileDownload(Path.of("本地路径"));
HttpResponse.BodyHandlers.ofFile(Path.of("本地路径"));
HttpResponse.BodyHandlers.ofPublisher();
HttpResponse.BodyHandlers.buffering();
HttpResponse.BodyHandlers.ofLines();
HttpResponse.BodyHandlers.fromSubscriber();
HttpResponse.BodyHandlers.fromLineSubscriber();
异步请求
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
// 获取响应body
.thenApply(HttpResponse::body)
// 将响应body转为json
.thenApply(JSONUtil::parseObj);
并发请求
public void getURIs(List<URI> uris) {
HttpClient client = HttpClient.newHttpClient();
List<HttpRequest> requests = uris.stream()
.map(HttpRequest::newBuilder)
.map(reqBuilder -> reqBuilder.build())
.collect(toList());
CompletableFuture.allOf(requests.stream()
.map(request -> client.sendAsync(request, asString()))
.toArray(CompletableFuture<?>[]::new))
.join();
}
CookieManager
var cookieManager = new CookieManager();
var client = HttpClient.newBuilder()
.cookieHandler(cookieManager)
.build();
参考资料:
https://github.com/apachecn/apachecn-java-zh/blob/master/docs/java-coding-prob/13.md