加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java中,利用HttpAsyncClient进行异步请求

(2016-07-07 16:00:25)
标签:

it

closeablehttpasynccl

http异步请求

分类: it
最近,因项目需要,用到了HttpAsyncClient进行异步请求。
所用到的jar包:httpasyncclient-4.1.1.jar、httpclient-4.5.2.jar、httpcore-4.4.5.jar
实例如下:
public static void main(String[] args)
throws InterruptedException, ExecutionException, UnsupportedOperationException, IOException {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
List UserParams = new ArrayList();
String url = "www.baidu.com";
// 添加请求参数
UserParams.add(new BasicNameValuePair("userName", "xiaosan"));
UserParams.add(new BasicNameValuePair("age", "18"));
UserParams.add(new BasicNameValuePair("sex", "男"));
httpclient.start();
final HttpPost request = new HttpPost(url);
request.setEntity(new UrlEncodedFormEntity(UserParams, Consts.UTF_8.name()));
HttpResponse response = (HttpResponse) httpclient.execute(request, null).get();
InputStream inputStream;
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
StringBuilder stringBuilder = new StringBuilder();
char[] tmp = new char[1024];
Reader reader = new InputStreamReader(inputStream, "utf-8");
int line;
while ((line = reader.read(tmp)) != -1) {
stringBuilder.append(tmp, 0, line);
}
String responseStr = stringBuilder.toString();// 请求返回的内容
}
httpclient.close();
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有