1. Overview
1.概述
This cookbook shows how to use the Apache HttpClient in a variety of examples and use-cases.
本手册展示了如何在各种实例和使用情况下使用Apache HttpClient 。
The focus is on HttpClient 4.3.x and above, so some of the examples may not work with the older versions of the API.
重点是HttpClient 4.3.x及以上版本,所以有些例子可能无法在旧版本的API上运行。
The format of the cookbook is example focused and practical – no extraneous details and explanations necessary.
烹饪书的格式是以实例为中心,而且很实用–没有多余的细节和解释的必要。
If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.
如果你想更深入地了解你可以用HttpClient做的其他很酷的事情–请到主要的HttpClient教程。
2. Cookbook
2.烹饪书
create the http client
创建http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
send basic GET request
发送基本的GET请求
instance.execute(new HttpGet("http://www.google.com"));
get the Status Code of the HTTP Response
获取HTTP响应的状态代码
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
get the Media Type of the response
获取响应的媒体类型
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
assertThat(contentMimeType, equalTo(ContentType.TEXT_HTML.getMimeType()));
get the body of the response
获取响应的主体
CloseableHttpResponse response = instance.execute(new HttpGet("http://www.google.com"));
String bodyAsString = EntityUtils.toString(response.getEntity());
assertThat(bodyAsString, notNullValue());
configure the timeout on a request
配置一个请求的超时时间。
@Test(expected = SocketTimeoutException.class)
public void givenLowTimeout_whenExecutingRequestWithTimeout_thenException()
throws ClientProtocolException, IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(1000).setConnectTimeout(1000).setSocketTimeout(1000).build();
HttpGet request = new HttpGet(SAMPLE_URL);
request.setConfig(requestConfig);
instance.execute(request);
}
configure timeout on the entire client
在整个客户端上配置超时。
RequestConfig requestConfig = RequestConfig.custom().
setConnectionRequestTimeout(1000).setConnectTimeout(1000).setSocketTimeout(1000).build();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
send a POST request
发送一个POST请求
instance.execute(new HttpPost(SAMPLE_URL));
add parameters to a 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));
configure how redirect are handled for an HTTP Request
配置如何处理一个HTTP请求的重定向。
CloseableHttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
CloseableHttpResponse response = instance.execute(new HttpGet("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
configure the headers for a request
为一个请求配置头信息。
HttpGet request = new HttpGet(SAMPLE_URL);
request.addHeader(HttpHeaders.ACCEPT, "application/xml");
response = instance.execute(request);
get the headers from the response
从响应中获取头信息
CloseableHttpResponse response = instance.execute(new HttpGet(SAMPLE_URL));
Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
assertThat(headers, not(emptyArray()));
close/release resources
关闭/释放资源
response = instance.execute(new HttpGet(SAMPLE_URL));
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
instream.close();
}
} finally {
response.close();
}
3. Go Deep Into HttpClient
3.深入了解HttpClient
The HttpClient library is quite a powerful tool if used correctly – if you want to start exploring what the client can do – check out some of the tutorials:
如果使用得当,HttpClient库是一个相当强大的工具–如果你想开始探索该客户端能做什么–请查看一些教程。
You can also dig a lot deeper into the HttpClient by exploring the entire series.
你还可以通过探索整个系列来更深入地了解HttpClient。
4. Conclusion
4.结论
This format is a bit different from how I usually structure my articles – I’m publishing some of my internal development cookbooks on a given topic – on Google Guava, Hamcrest and Mockito – and now HttpClient. The goal is to have this information readily available online – and to add to it whenever I run into a new useful example.
这种格式与我通常的文章结构有些不同–我就某一主题发布一些内部开发食谱–在Google Guava>上。Hamcrest和Mockito – 现在还有HttpClient。我们的目标是让这些信息可以随时在线获取–并且在我遇到新的有用的例子时对其进行补充。
The implementation of all these examples and code snippets can be found in over on GitHub.
所有这些例子和代码片段的实现可以在GitHub上找到。
This is a Maven based project, so it should be easy to import and run as it is.
这是一个基于Maven的项目,所以它应该很容易导入并按原样运行。