关于Apache的HttpClient一些使用心得

HttpClient官方说明

  1. 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.

  2. HttpClient 4.5 requires Java 1.5 or newer.

  3. The below code fragment illustrates the execution of HTTP GET and POST requests using the HttpClient native API.

    API:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/HttpClient.html

简单示例

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;
	 			    }
	 			});
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值