本文更新日期:2019年10月13日

前言

最近汇总了几个群成员经常提出的问题,统一做下解答,如下文所述。

一、HttpClient官网

http://hc.apache.org/

二、HttpClient最新版本

HttpClient 4.5.10

maven依赖:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.10</version>
</dependency>

三、HttpClient使用步骤

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1、创建HttpClient对象。常见的方式有两种:http://www.httpclient.cn/archives/43.html

2、创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3、如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4、调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5、调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6、释放连接。无论执行方法是否成功,都必须释放连接

四、DefaultHttpClient已经被废弃

官方文档不推荐使用DefaultHttpClient了,请注意以下核心类的升级关系:

DefaultHttpClient —> CloseableHttpClient
HttpResponse —> CloseableHttpResponse

官方给出了新API的样例,如下所示:

Get方法:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response = httpclient.execute(httpGet);
    
//建立的http连接,仍旧被response保持着,允许我们从网络socket中获取返回的数据
//为了释放资源,我们必须手动消耗掉response或者取消连接(使用CloseableHttpResponse类的close方法)
try 
{
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
} 
finally 
{
    response.close();
}

Post方法:

HttpPost httpPost = new HttpPost("http://targethost/login");
//拼接参数
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpclient.execute(httpPost);
try 
{
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
} 
finally 
{
    response.close();
}

再往下看HttpClients的源码,具体的实现都在HttpClientBuilder的build方法中,有兴趣的可以去apache看源码。

public static CloseableHttpClient createDefault() 
{
    return HttpClientBuilder.create().build();
}