java.net.http.HttpClient 是 jdk11 中正式启用的一个 http 工具类(在 jdk9 的时候就已经存在),官方想要取代 HttpURLConnection 和 Apache HttpClient 等比较古老的开发工具
HttpClient 的API //创建一个 HttpClient public static Builder newBuilder() public static HttpClient newHttpClient() // HttpClient.newBuilder().build() //webSocket协议的请求客户端的构建者 public WebSocket.Builder newWebSocketBuilder() public abstract Optional<CookieHandler> cookieHandler() // 获取 CookieHandler public abstract Optional<Duration> connectTimeout() public abstract Redirect followRedirects() public abstract Optional<ProxySelector> proxy() public abstract SSLContext sslContext() public abstract Optional<Executor> executor()HttpClient.Builder 的 API
//缓存cookie设置 public Builder cookieHandler(CookieHandler cookieHandler); //连接超时时间 public Builder connectTimeout(Duration duration); // 证书信息设置 public Builder sslContext(SSLContext sslContext); // SSL / TLS / DTLS连接的参数 设置 public Builder sslParameters(SSLParameters sslParameters); //涉及到异步操作用到的 线程池 public Builder executor(Executor executor); // 是否支持重定向 Redirect.SAME_PROTOCOL public Builder followRedirects(Redirect policy); // 协议版本,HTTP/1.1 还是 HTTP/2 public Builder version(HttpClient.Version version); public Builder priority(int priority); //配置代理 public Builder proxy(ProxySelector proxySelector); //认证 Authenticator.getDefault() public Builder authenticator(Authenticator authenticator);HttpClient 调用 API
//阻塞调用 <T> HttpResponse<T> send(HttpRequest request, HttpResponse.BodyHandler<T> responseBodyHandler) //相当于使用了多路复用I/O <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, BodyHandler<T> responseBodyHandler) abstract <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, BodyHandler<T> responseBodyHandler, PushPromiseHandler<T> pushPromiseHandler) HttpRequest 构建的 API