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; 
  
}

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10485.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论