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
原文:http://www.cnblogs.com/hisunhyx/p/5027419.html