CodeGym/Java 课程/模块 3/新的 HttpClient

新的 HttpClient

可用

1.1 HttpClient介绍

从 JDK 11 开始,Java 平台的开发人员向 JDK 添加了一个强大的新工具来发出 http 请求,java.net.http. 它包含四个关键类:

  • HTTP客户端
  • HTTP请求
  • HTTP响应
  • 网络套接字

这些是非常强大的类,允许您使用HTTP,HTTP/2和执行所有可能类型的请求WebSocket

此外,您可以使用这些类来发出同步和异步 http 请求。

发出http请求包括以下部分:

  1. 创建对象HttpClient
  2. 创建对象HttpRequest
  3. send()使用or方法发送请求sendAsync()
  4. 响应处理HttpResponse

此类请求的示例:

HttpClient client = HttpClient.newBuilder()
        .version(Version.HTTP_1_1)
        .followRedirects(Redirect.NORMAL)
        .connectTimeout(Duration.ofSeconds(20))
        .proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
        .authenticator(Authenticator.getDefault())
        .build();

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

1.2 声明方式

在上面的例子中,您看到了一个所谓的声明式代码编写方法的例子。让我们看一下示例的第一部分:

HttpClient client = HttpClient.newBuilder()
.version(Version.HTTP_1_1)
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.proxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)))
.authenticator(Authenticator.getDefault())
.build();

这段代码以经典风格编写会是什么样子:

HttpClient client = HttpClient.new();
client.setVersion(Version.HTTP_1_1);
client.setFollowRedirects(Redirect.NORMAL);
client.setConnectTimeout(Duration.ofSeconds(20));
client.setProxy(ProxySelector.of(new InetSocketAddress("proxy.example.com", 80)));
client.setAuthenticator(Authenticator.getDefault());

在代码中使用声明性方法时,有两件事发生了变化。 首先,所有类方法HttpClient 都返回它们自己的对象,这允许您以链的形式组织代码。

经典代码:
HttpClient client = HttpClient.new();
client.setVersion(Version.HTTP_1_1);
client.setFollowRedirects(Redirect.NORMAL);
client.setConnectTimeout(Duration.ofSeconds(20));
client.setAuthenticator(Authenticator.getDefault());
作为链条:
HttpClient client = HttpClient.new() .setVersion(Version.HTTP_1_1) .setFollowRedirects(Redirect.NORMAL). setConnectTimeout(Duration.ofSeconds(20)) .setAuthenticator(Authenticator.getDefault());
我们将每个方法转移到单独的一行(这是一个长语句)
HttpClient client = HttpClient.new()
.setVersion(Version.HTTP_1_1)
.setFollowRedirects(Redirect.NORMAL)
.setConnectTimeout(Duration.ofSeconds(20))
.setAuthenticator(Authenticator.getDefault());

其次,从方法中删除了前缀set,这使您可以更紧凑地编写代码:

曾是
HttpClient client = HttpClient.new()
.setVersion(Version.HTTP_1_1)
.setFollowRedirects(Redirect.NORMAL)
.setConnectTimeout(Duration.ofSeconds(20))
.setAuthenticator(Authenticator.getDefault());
它变成了
HttpClient client = HttpClient.new()
.version(Version.HTTP_1_1)
.followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(20))
.authenticator(Authenticator.getDefault());

这样的代码更容易阅读,但更难编写。

还有一点很重要。在这个例子中,使用了建造者模式。在某些情况下,创建对象是一个复杂的过程。因此,他们更愿意将其形式化:以条件方法调用开始begin(),以条件方法调用结束end()

在我们分析的示例中,该方法HttpClient.newBuilder()返回一个对象HttpClient.Builder(这是该类的一个内部实用程序类HttpClient)。version()仅在此服务对象上调用该类型的所有方法。嗯,方法的调用build()标志着对象构造的结束并返回对象HttpClient

评论
  • 受欢迎
你必须先登录才能发表评论
此页面还没有任何评论