新的 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

留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言