前几天研究了Java的异步处理CompletableFuture,它是在1.8中新加的,jdk11中的HttpClient刚好也用到了,顺便说一下怎么使用,以前可能会用第三方的http处理库,现在Java11已经自带了,而且用起来也很方便。
java.net.http.HttpClient
这个类主要是用来发送http请求的,是一个抽象类,通过builder来创建实例。
HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(6))
.build();
builder几个常用的设置:
两个发送请求的方法:
同步请求
request:发送的请求
responseBodyHandler:响应结果处理器
HttpResponse:http响应
public abstract <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) throws IOException, InterruptedException
异步请求
request:发送的请求
responseBodyHandler:响应结果处理器
CompletableFuture
public abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler)
java.net.http.HttpRequest
包装要发送的请求,比如请求链接,请求方法,请求体,请求头等等。同样是一个抽象类,使用builder来构造实例。
HttpRequest request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.method("GET", bodyPublisher)
.timeout(Duration.ofSeconds(2))
.uri(URI.create(""))
.build();
builder几个常用的设置:
HttpRequest.BodyPublisher
主要是将普通的Java请求对象转换为字节缓冲流作为请求体发送。为接口,其实现类为HttpRequest.BodyPublishers
。将一些常见的Java对象转换为字节缓冲流。
noBody()
ofByteArray(byte[] buf)
ofFile(Path path)
ofInputStream(Supplier extends InputStream> streamSupplier)
ofString(String s, Charset charset)
// Request body from a String
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "text/plain; charset=UTF-8")
.POST(BodyPublishers.ofString("some body text"))
.build();
// Request body from a File
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
// Request body from a byte array
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://foo.com/"))
.POST(BodyPublishers.ofByteArray(new byte[] {
... }))
.build();
java.net.http.HttpResponse
http响应,不能直接创建,当发送请求之后作为结果返回。当响应状态码和标头接收到时,响应才可用。
接受字符串响应体:
HttpResponse<String> response = client
.send(request, BodyHandlers.ofString());
HttpResponse.BodyHandler
响应体处理器,将字节转为Java对象。为接口,实现类为HttpResponse.BodyHandlers
。
java.net.CookieHandler
Java1.5,抽象类,进行Cookie处理。子类为CookieManager,默认是将Cookie存储与内存中。
基本使用流程:
client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(2))
.cookieHandler(new CookieManager())
.build();
HttpRequest.BodyPublisher publisher = HttpRequest.BodyPublishers.ofString(body);
request = HttpRequest.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.headers("Content-type", "application/x-www-form-urlencoded")
.method("POST", publisher)
.timeout(Duration.ofSeconds(2))
.uri(URI.create(HOST + url))
.build();
发送请求,接收响应
同步:
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
response.statusCode();响应码
response.body();响应体
异步:
CompletableFuture<HttpResponse<String>> response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
response.thenApply(response -> response.body())
.thenAccept(body -> {
System.out.println(body);
});