HttpClient 4 简易手册

简要

这个简易手册将告诉我们Apache HttpClient 4 的一些使用示例。 在这里主要是讲HttpClient 4.3.x或以上的版本的使用事例。在一些老版本中可能是无法使用的。 以下的示例。只是功能的实现,没有详细的说明和必要的解释。

示例

创建HTTP链接

CloseableHttpClient client = HttpClientBuilder.create().build();
发送一个GET请求
instance.execute(new HttpGet("http://www.google.com"));
从HTTP Response中获取返回状态
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); 获取响应的媒体类型
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
获取响应的body
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
配置超时请求
@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);
}
配置整个客户端超市请求
RequestConfig requestConfig = RequestConfig.custom().
    setConnectionRequestTimeout(50).setConnectTimeout(50).setSocketTimeout(50).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
发送一个POST请求
instance.execute(new HttpPost(SAMPLE_URL));
request 添加参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("key1", "value1"));
params.add(new BasicNameValuePair("key2", "value2"));
request.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
HTTP Request 重定向处理
CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
配置请求的header
CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()))
关闭释放资源
response = instance.execute(new HttpGet(SAMPLE_URL));
try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        instream.close();
    }
} finally {
    response.close();
}

结束

所有这些例子都可以在作者的[weblink url="https://github.com/eugenp/tutorials/tree/master/httpclient#readme"]git 项目[/weblink] 里找到.是在eclipse环境下开发的。应该很容易跑起来

你可能感兴趣的:(httpclient)