AsyncHttpClient
是一个非阻塞的 HTTP 客户端库,用于 Java 和 Android 平台。它允许你异步地发送 HTTP 请求,这对于提高应用程序性能和响应性非常有用。以下是使用 AsyncHttpClient 的一些基本示例。
1. 添加依赖
对于 Maven,你可以在 pom.xml
文件中添加如下依赖:
<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.12.3</version>
</dependency>
对于 Gradle,你可以在 build.gradle
文件中添加如下依赖:
implementation 'org.asynchttpclient:async-http-client:2.12.3'
2. 创建 AsyncHttpClient 实例
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
public class Main {
public static void main(String[] args) {
AsyncHttpClient client = new DefaultAsyncHttpClient();
}
}
3. 发送 GET 请求
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import java.util.concurrent.ExecutionException;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
ListenableFuture<Response> future = client.prepareGet("https://api.example.com/data")
.addHeader("accept", "application/json")
.execute();
Response response = future.get(); // 阻塞直到响应返回
System.out.println(response.getStatusCode()); // 打印状态码
System.out.println(response.getResponseBody()); // 打印响应体
}
}
}
4. 发送 POST 请求
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.ListenableFuture;
import org.asynchttpclient.Response;
import java.util.concurrent.ExecutionException;
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
ListenableFuture<Response> future = client.preparePost("https://api.example.com/data")
.addHeader("content-type", "application/json")
.setBody("{ \"key\": \"value\" }")
.execute();
Response response = future.get();
System.out.println(response.getStatusCode());
System.out.println(response.getResponseBody());
}
}
}
5. 使用回调处理异步响应
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Response;
public class Main {
public static void main(String[] args) {
try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
client.prepareGet("https://api.example.com/data")
.addHeader("accept", "application/json")
.execute(new AsyncCompletionHandler<Void>() {
@Override
public Void onCompleted(Response response) throws Exception {
System.out.println("Status Code: " + response.getStatusCode());
System.out.println("Response Body: " + response.getResponseBody());
return null;
}
@Override
public void onError(Throwable t) {
System.err.println("Error: " + t.getMessage());
}
});
}
}
}
6. 使用 CompletableFuture 处理异步响应
从 AsyncHttpClient 2.7.0 版本开始,你可以使用 CompletableFuture
来处理异步响应,这使得异步编程更加简洁。
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Response;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
CompletableFuture<Response> future = client.prepareGet("https://api.example.com/data")
.addHeader("accept", "application/json")
.execute();
future.thenAccept(response -> {
System.out.println("Status Code: " + response.getStatusCode());
System.out.println("Response Body: " + response.getResponseBody());
}).exceptionally(ex -> {
System.err.println("Error: " + ex.getMessage());
return null;
});
}
}
}
这些示例演示了如何使用 AsyncHttpClient 发送 GET 和 POST 请求,并处理响应。你可以根据实际需求调整这些代码。AsyncHttpClient 还提供了许多高级功能,如 SSL/TLS 支持、代理配置、请求重试等,你可以查阅官方文档了解更多详细信息。