关于Apache的HttpClient一些使用心得
HttpClient官方说明
-
Download ‘Binary’ package of the latest HttpClient 4.5 release or configure dependency on HttpClient and Fluent HC modules using a dependency manager of your choice as described here.
-
HttpClient 4.5 requires Java 1.5 or newer.
-
The below code fragment illustrates the execution of HTTP GET and POST requests using the HttpClient native API.
简单示例
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
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 response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response2.close();
}
说明:
- HttpClient接口仅表示HTTP请求执行的最基本合同。它对请求执行过程没有任何限制或特定细节,并且将状态管理,身份验证和重定向处理的细节留给单独的实现。
- HttpClients是CloseableHttpClient实例的工厂方法
- createDefault() 是CloseableHttpClient默认配置创建实例方法
- HttpGet http get请求HttpGet()参数可以是URI 或String类型的链接
- HttpPost POST旨在允许统一的方法来涵盖以下功能:
现有资源的注释
将消息发布到公告板,新闻组,邮件列表或类似的文章组
向数据处理过程提供数据块,例如提交表单的结果
通过追加操作扩展数据库 - execute执行HTTP请求
- response 为返回信息
- response.getStatusLine()获取状态码
- response.getEntity() 获取返回的body
忽略安全证书设置
/**
* httpclient4.5
* 忽略安全证书
* @return
*/
public static HttpClientConnectionManager init(){
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslContext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry registry = RegistryBuilder
. create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslsf).build();
return new PoolingHttpClientConnectionManager(registry);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
说明:
- SSLContext: 此类的实例表示安全套接字协议的实现, 它是SSLSocketFactory、SSLServerSocketFactory和SSLEngine的工厂
- SSLContexts:SSLContext 工厂,custom() 用于创建普通的SSLContext
- loadTrustMaterial 配置忽略掉对服务器端证书的校验 使用TrustStrategy在不咨询实际SSL上下文中配置的信任管理器的情况下建立证书可信度的策略
- 忽略证书验证 - ALLOW_ALL_HOSTNAME_VERIFIER
- Registry 通用注册表 RegistryBuilder用于创建Registry 实例
- PoolingHttpClientConnectionManager 是一个HttpClientConnection的连接池,可以为多线程提供并发请求服务。主要作用就是分配连接,回收连接等。同一个route的请求,会优先使用连接池提供的空闲长连接
设置自动重定向
client.setRedirectHandler(new DefaultRedirectHandler() {
@Override
public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
boolean isRedirect = super.isRedirectRequested(response, context);
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) {
return true;
}
}
return isRedirect;
}
});