首页 > Web开发 > 详细

HttpClient常用的一些常识

时间:2015-12-07 22:14:48      阅读:353      评论:0      收藏:0      [点我收藏+]

HttpClient是目前我们通讯组件中最常见的一个Api了吧。至少从我目前接触到与外部系统通讯的话是这样的。下面我将我自己常用的一些知识总结一下。

因为本猿也是边写边总结,有啥不对的还望多多指出。

1:利用httpClient发送https请求。

第一次遇到这种情况是开发与微信支付的接口。适用情形https请求,报文格式:字符串(包含json字符串和xml字符串)。

public String doPost(String url,String charset,String reqXmlData){
  HttpClient httpClient = null;
  HttpPost httpPost = null;
  String result = null;
  try{
   //这里是关键,SSLClient继承了DefaultHttpClient 忽略https校验过程。SSLClient具体如下。
   httpClient = new SSLClient();
   logger.info("call weixin pay url:"+url);
   httpPost = new HttpPost(url);
   logger.info("call weixin pay requestXmlData:"+reqXmlData);
   //设置最简单的字符串请求参数
   StringEntity strEntity = new StringEntity(reqXmlData, charset);
   httpPost.setEntity(strEntity);
   HttpResponse response = httpClient.execute(httpPost);
   int code = response.getStatusLine().getStatusCode();   
   if(code == 200){
    HttpEntity resEntity = response.getEntity();
    if(resEntity != null){
     result = EntityUtils.toString(resEntity,charset);
    }
   }else{
    //这里就不对其他code处理了
   }
   logger.info("call weixin pay responseXmlData:"+result);
  }catch(Exception ex){
   ex.printStackTrace();
  }finally{
   if (httpClient != null){
    httpClient = null;
   }
  }
  return result;
 }

/**
 * 用于进行Https请求的HttpClient
 */
public class SSLClient extends DefaultHttpClient{
 public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = this.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    }
}

 

好了,今天就先更新到这里了。下班肥家。20151207

HttpClient常用的一些常识

原文:http://www.cnblogs.com/hisunhyx/p/5027419.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!