写一个HttpPost异步请求
时间: 2024-06-10 17:06:26 浏览: 70
一个Http异步请求的例子
可以的,下面是一个使用HttpPost异步请求的示例代码:
```
// 创建一个HttpPost对象
HttpPost httpPost = new HttpPost("http://www.example.com/api");
// 创建一个RequestConfig对象,设置请求超时时间和连接超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.build();
// 设置RequestConfig对象到HttpPost对象
httpPost.setConfig(requestConfig);
// 创建一个CloseableHttpAsyncClient对象
CloseableHttpAsyncClient httpAsyncClient = HttpAsyncClients.createDefault();
// 创建一个BasicNameValuePair对象列表,用于设置请求参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "张三"));
params.add(new BasicNameValuePair("age", "18"));
// 创建一个UrlEncodedFormEntity对象,用于通过HttpPost请求发送参数
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
// 设置UrlEncodedFormEntity对象到HttpPost对象
httpPost.setEntity(formEntity);
// 发送HttpPost异步请求
httpAsyncClient.execute(httpPost, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse response) {
try {
// 获取响应实体
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 打印响应内容
System.out.println(EntityUtils.toString(responseEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void failed(Exception ex) {
// 处理请求失败情况
}
@Override
public void cancelled() {
// 处理请求取消情况
}
});
// 关闭CloseableHttpAsyncClient对象
httpAsyncClient.close();
```
阅读全文