httpclient4.3x的ssl请求工具类

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
/**
 * post提交工具类
 *
 * @param url     访问的url
 * @param map     post参数
 * @param charset 编码
 * @return 响应结束的返回字符串
 */
public static String doPost(String url, Map<String, String> map, String charset) throws Exception {
    HttpClient httpClient = null;
    HttpPost httpPost = null;
    String result = null;
    httpPost = new HttpPost(url);
    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);
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    //设置参数
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    Iterator iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
        Entry<String, String> elem = (Entry<String, String>) iterator.next();
        list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
    }
    if (list.size() > 0) {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
        httpPost.setEntity(entity);
    }
    HttpResponse response = httpClient.execute(httpPost);
    if (response != null) {
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            result = EntityUtils.toString(resEntity, charset);
        }
    }
    return result;
 
}

标签: ssl

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Android生成彩色的二维码

下一篇: Android 获得手机屏幕大小