Apache HttpClient 4.3开发指南

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:02   5192   0

一、概述

Apache HttpClient 4系列已经发布很久了,但由于它与HttpClient 3.x版本完全不兼容,以至于业内采用此库的公司较少,在互联网上也少有相关的文档资料分享。

本文旨在写一个简要的Apache HttpClient 4.3开发指南,帮助开发者快速上手Apache HttpClient 4.3.x库。

要注意的是,本文档中的代码在低于HttpClient 4.3版本的地方可能不能运行。

二、开发手册

1、创建HTTP客户端

CloseableHttpClient client = HttpClientBuilder.create().build();

2、发送基本的GET请求

instance.execute(new HttpGet(“http://www.baidu.com”));

3、获取HTTP响应的状态码

String url = “http://www.baidu.com”;
CloseableHttpResponse response = instance.execute(new HttpGet(url));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

4、获取响应的媒体类型

String url = “http://www.baidu.com”;
CloseableHttpResponse response = instance.execute(new HttpGet(url));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));

5、获取响应的BODY部分

String url = “http://www.baidu.com”;
CloseableHttpResponse response = instance.execute(new HttpGet(url));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());

6、配置请求的超时设置

@Test(expected=SocketTimeoutException.class)
public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException() throws ClientProtocolException, IOException{
    RequestConfig requestConfig = RequestConfig.custom()
 .setConnectionRequestTimeout(50).setConnectTimeout(50)
 .setSocketTimeout(50).build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    request.setConfig(requestConfig);
    instance.execute(request);
}

7、发送POST请求

instance.execute(new HttpPost(SAMPLE_URL));

8、为HTTP请求配置重定向

CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
assertThat(reponse.getStatusLine().getStatusCode(), equalTo(301));

9、配置请求的HEADER部分

HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, “application/xml”);
response = instance.execute(request);

10、获取响应的HEADER部分

CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));

11、关闭或释放资源

response = instance.execute(new HttpGet(SAMPLE_URL));
try{
  HttpEntity entity = response.getEntity();
  if(entity!=null){
InputStream instream = entity.getContent();
instream.close();
  }
} finally{
  response.close();
}

12.给请求添加参数

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", "12348"));
params.add(new BasicNameValuePair("param2", "1"));
//request 是GET或POSTMethod对象
request.setEntity(new UrlEncodedFormEntity(params,"utf-8"));


转载于:https://my.oschina.net/quttap/blog/200281

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP