httpclient4.3x ssl请求工具类

/**
 * 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;

}


你可能感兴趣的:(java,httpclient)