乐趣区

关于人工智能:64-HttpClient

1. 什么是 HttpClient?

HttpClient 是 Java 11 中引入的一个新个性,用于反对同步和异步发送 HTTP 申请以及解决 HTTP 响应。它提供了简略易用的 API,使得发送 HTTP 申请变得非常简单。

2. HttpClient 的次要组件

HttpClient 由以下几个次要组件组成:

  • HttpClient:用于发送申请的次要类。
  • HttpRequest:示意一个 HTTP 申请。
  • HttpResponse:示意一个 HTTP 响应。

3. 发送 GET 申请

要应用 HttpClient 发送 GET 申请,能够创立一个 HttpClient 对象,而后创立一个 HttpRequest 对象并设置申请办法为 GET。最初,应用 HttpClient 的 send() 办法发送申请并获取响应。以下是一个简略示例:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientGetExample {public static void main(String[] args) {
        try {HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://www.example.com/"))
                    .GET()
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.statusCode());
            System.out.println(response.body());
        } catch (Exception e) {e.printStackTrace();
        }
    }
}

4. 发送 POST 申请

要应用 HttpClient 发送 POST 申请,能够创立一个 HttpClient 对象,而后创立一个 HttpRequest 对象并设置申请办法为 POST。还须要设置申请体,例如表单数据或 JSON 数据。最初,应用 HttpClient 的 send() 办法发送申请并获取响应。以下是一个简略示例:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

public class HttpClientPostExample {public static void main(String[] args) {
        try {HttpClient client = HttpClient.newHttpClient();
            String postData = "username=user&password=pass";
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://www.example.com/login"))
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .POST(HttpRequest.BodyPublishers.ofString(postData))
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.statusCode());
            System.out.println(response.body());
        } catch (Exception e) {e.printStackTrace();
        }
    }
}

5. 异步申请

HttpClient 还反对异步发送 HTTP 申请。要发送异步申请,能够应用 HttpClient 的 sendAsync() 办法。以下是一个简略示例:

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpClientAsyncExample {public static void main(String[] args) {
        try {HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://www.example.com/"))
                    .GET()
                    .build();

            client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                    .thenApply(HttpResponse::body)
                    .thenAccept(System.out::println)
                    .join();} catch (Exception e) {e.printStackTrace();
        }
    }
}

6. 自定义 HttpClient

能够通过 HttpClient.Builder 类自定义 HttpClient,例如设置超时、代理、重定向策略等。以下是一个简略示例,演示如何设置超时和代理:

import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class CustomHttpClientExample {public static void main(String[] args) {
        try {HttpClient client = HttpClient.newBuilder()
                    .connectTimeout(Duration.ofSeconds(5))
                    .proxy(ProxySelector.of(new InetSocketAddress("myproxy.example.com", 8080)))
                    .build();

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://www.example.com/"))
                    .GET()
                    .build();

            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.statusCode());
            System.out.println(response.body());
        } catch (Exception e) {e.printStackTrace();
        }
    }
}

当初,您曾经理解了 Java 的 HttpClient 的基本概念和用法。实际上,还有许多其余性能和配置能够摸索。在理论我的项目中,您可能须要依据具体需要调整 HttpClient 的配置。心愿这些示例能帮忙您更好地了解 Java 网络编程中的 HttpClient 组件。
举荐浏览:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

退出移动版