httpclient5异步发送请求
时间: 2023-08-31 09:05:06 浏览: 166
HttpClient异步请求
HttpClient 5是Apache HttpClient项目的最新版本,它具有更好的性能和更好的可扩展性。以下是使用HttpClient 5异步发送请求的示例代码:
```java
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.hc.client5.http.async.methods.*;
import org.apache.hc.client5.http.async.methods.HttpAsyncMethods;
import org.apache.hc.client5.http.async.methods.HttpAsyncResponseConsumer;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.*;
import org.apache.hc.core5.http.nio.AsyncEntityConsumer;
import org.apache.hc.core5.http.nio.BasicAsyncResponseConsumer;
import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
public class AsyncHttpClientExample {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
httpclient.start();
// Execute a simple request asynchronously
Future<HttpResponse> future = httpclient.execute(HttpAsyncMethods.createGet("https://www.example.com/"), new BasicAsyncResponseConsumer(), null);
// Wait for the request to complete
HttpResponse response = future.get();
System.out.println(response.getCode() + " " + response.getReasonPhrase());
// Execute a request with a request body and response body asynchronously
HttpAsyncRequestProducer producer = HttpAsyncMethods.createPost("https://www.example.com/", "Hello, world!", ContentType.TEXT_PLAIN);
AsyncEntityConsumer<String> consumer = new StringAsyncEntityConsumer();
HttpAsyncResponseConsumer<HttpResponse> responseConsumer = HttpAsyncMethods.createConsumer(consumer);
Future<HttpResponse> future2 = httpclient.execute(producer, responseConsumer, null);
// Wait for the request to complete
HttpResponse response2 = future2.get();
System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
System.out.println(consumer.getEntity());
}
}
}
```
在上面的示例中,我们首先创建一个CloseableHttpAsyncClient对象,然后使用它发送两个请求,一个是简单的GET请求,另一个是带有请求体和响应体的POST请求。
对于每个请求,我们使用HttpAsyncMethods类创建请求对象和响应消费者对象。对于GET请求,我们使用BasicAsyncResponseConsumer作为响应消费者,它将响应作为HttpResponse对象返回。对于POST请求,我们使用StringAsyncEntityConsumer作为实体消费者,它将响应实体作为字符串返回。然后我们使用execute方法异步发送请求,并在Future对象上使用get方法等待响应。
注意,在使用HttpClient 5异步发送请求时需要调用start方法启动CloseableHttpAsyncClient对象,并在使用完毕后调用close方法关闭它。
阅读全文