java 使用Apache的框架,写一个http异步调用的案例
时间: 2024-04-03 09:37:01 浏览: 180
一个Http异步请求的例子
好的,下面是一个使用Apache的HttpAsyncClient框架进行异步调用的Java案例:
```java
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
public class HttpAsyncClientExample {
public static void main(String[] args) throws IOException, InterruptedException {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
httpclient.start();
String url = "https://www.example.com";
HttpGet request = new HttpGet(url);
CompletableFuture<String> future = new CompletableFuture<>();
httpclient.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
HttpEntity entity = result.getEntity();
try {
String body = EntityUtils.toString(entity);
future.complete(body);
} catch (IOException e) {
future.completeExceptionally(e);
}
}
@Override
public void failed(Exception ex) {
future.completeExceptionally(ex);
}
@Override
public void cancelled() {
future.cancel(true);
}
});
String response = future.get();
System.out.println(response);
httpclient.close();
}
}
```
这个案例使用了HttpAsyncClient的异步调用方式,通过FutureCallback回调函数来处理异步响应。首先创建一个CloseableHttpAsyncClient对象,调用start()方法启动客户端。然后创建一个HttpGet请求对象,并以此为参数调用execute方法,该方法会异步地发送请求。execute方法的第二个参数是一个FutureCallback对象,当请求完成时,会回调这个对象的completed方法,可以在completed方法中获取到响应的实体,并将其转化为字符串。如果请求失败,则回调failed方法,如果请求被取消,则回调cancelled方法。最后通过CompletableFuture的get方法来获取异步调用的结果,并输出结果。最后调用close方法关闭客户端。
阅读全文