Java9 HTTP2.0 API入门与实践

简述

如果您需要使用Java语言来请求HTTP资源,那么你可能会遇到多种解决方案,你最终可能会以一种合理的方式来达成这个目的 —– 引用第三方包。

Java9除了有模块化特性之外,还附带了一个全新的HTTP客户端API。不仅支持HTTP2.0,还提供了一套有亲和力的API。

HTTP2.0是啥子东东?

HTTP2.0带来了令人手舞足蹈的新特性:(这里不来自原文)

  • 二进制分帧
  • 请求/响应管线化
  • 异步连接
  • 多路复用
  • 服务器推送流(Server Push技术)
  • 基于TCP的长连接
  • 首部压缩

一句话描述:http/2最大的特点是使用多路复用,对同一个域的服务器只建立一次TCP连接,加载多个资源,使用二进制帧传输,同时会对http头部进行压缩。

就这样,我们瞧上了丰满的HTTP2.0。

Incubator 模块

这里需要注意的是,在Java9中HTTP客户端的构建需要依赖于一个Incubator模块,and more:

  • 在 JDK 9, 这个模块叫做 jdk.incubator.httpclient
  • incubator模块在JDK10将被 java.httpclient 所取代
  • JDK10在这方面将迎来重大突破(现在谁知道?)

Java 9的HTTP客户端API

基本上,通过HTTP进行通信时,会涉及到三个类: HttpClient将用于发送HttpRequest和接收HttpResponse 。这API还是比较容易理解的,right? Let’s see:

基本示例:GET 请求,返回字符串

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://labs.consol.de/"))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());

System.out.println(response.statusCode());
System.out.println(response.body());
Java9 HTTP2.0 API入门与实践

很优雅,对不对? 没有 InputStreamReader 被涉及, - 转而是通过BodyHandler 来直接从响应中获取字符串。不多赘述,将在下文介绍BodyHandlers

虽然HttpClientHttpRequest并且HttpResponse是HTTP2.0通信中的主要参与者,但我们还是要与Builder配合使用。 Builder 提供了一套简明易懂的API。

HttpRequest.Builder

我们可以通过调用HttpRequest.newBuilder() 来获取一个HttpRequest.Builder 实例,就像第一个示例中那样。 我们将使用它来配置与特定请求相关的所有内容。下面是源代码:

// HttpRequest.Builder
public abstract static class Builder {
    // note: some methods left out for the sake of brevity
    public abstract Builder uri(URI uri);
    public abstract Builder version(HttpClient.Version version);
    public abstract Builder header(String name, String value);
    public abstract Builder timeout(Duration duration);
    public abstract Builder GET();
    public abstract Builder POST(BodyProcessor body);
    public abstract Builder PUT(BodyProcessor body);
    public abstract Builder DELETE(BodyProcessor body);
    public abstract HttpRequest build();
}
Java9 HTTP2.0 API入门与实践

可读性很好(自解释型), right? 采用链式方法调用来完成请求内容的配置,然后调用build()获取HttpRequest实例。

HttpClient.Builder

HttpRequest 类似,我们调用 HttpClient.newBuilder() 来获取 HttpClient.Builder 实例。它提供了一个API来配置一些关于我们的连接的更通用的东西。 下面是源代码:

// HttpClient.Builder
public abstract static class Builder {
    public abstract Builder cookieManager(CookieManager cookieManager);
    public abstract Builder sslContext(SSLContext sslContext);
    public abstract Builder sslParameters(SSLParameters sslParameters);
    public abstract Builder executor(Executor executor);
    public abstract Builder followRedirects(Redirect policy);
    public abstract Builder version(HttpClient.Version version);
    public abstract Builder priority(int priority);
    public abstract Builder proxy(ProxySelector selector);
    public abstract Builder authenticator(Authenticator a);
    public abstract HttpClient build();
}
Java9 HTTP2.0 API入门与实践

真是通体雪白!!良好的自解释性帮助IDE能够更好地达成你的目的。

更多Java 9 HTTP客户端应用示例

上面见识到了这套前景光明的API,下面让我们来看看更多的关于它的应用示例吧。

1. 保存GET请求到文件

将下载的文件保存到本地,使用HttpResponse.BodyHandler.asFile(Path):

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://labs.consol.de/"))
    .GET()
    .build();

Path tempFile = Files.createTempFile("consol-labs-home", ".html");
HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandler.asFile(tempFile));
System.out.println(response.statusCode());
System.out.println(response.body());

2. 通过POST上传文件

用POST上传本地文件也变得十分简单,使用HttpRequest.BodyProcessor:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("http://localhost:8080/upload/"))
    .POST(HttpRequest.BodyProcessor.fromFile(Paths.get("/tmp/file-to-upload.txt")))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.discard(null));
System.out.println(response.statusCode());

3. 异步HTTP请求

异步HTTP请求也变得简单,由HttpClient#sendAsync() 代替 HttpClient#send 。如果服务端支持,你甚至可以取消执行中的请求:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://labs.consol.de/"))
    .GET()
    .build();

CompletableFuture<HttpResponse<String>> response = client.sendAsync(request, HttpResponse.BodyHandler.asString());

Thread.sleep(5000);
if(response.isDone()) {
    System.out.println(response.get().statusCode());
    System.out.println(response.get().body());
} else {
    response.cancel(true);
    System.out.println("Request took more than 5 seconds... cancelling.");
}

4. 使用系统代理设置

HttpClient client = HttpClient.newBuilder()

     .proxy(ProxySelector.getDefault())
     .build();

 HttpRequest request = HttpRequest.newBuilder()
     .uri(new URI("https://labs.consol.de"))
     .GET()
     .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
 System.out.println(response.statusCode());
 System.out.println(response.body());

5.基本认证 Basic Authentication

HttpClient client = HttpClient.newBuilder()
    .authenticator(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("username", "password".toCharArray());
        }
    })
    .build();

HttpRequest request = HttpRequest.newBuilder()
    .uri(new URI("https://labs.consol.de"))
    .GET()
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
System.out.println(response.statusCode());
System.out.println(response.body());
Java9 HTTP2.0 API入门与实践

结论

上面的例子表明,使用Java 9的标准API来发送HTTP请求会更简便。 此外,我们将能以优雅的方式处理响应。当然,某些三方包也有类似喜人的功能,但总得选择一种体面的(decent)开箱即用的解决方案(大家闺秀即视感,2333)。

相关推荐