首页

通过apache的CloseableHttpClient的HttpClients.createDefault()实现忽略https安全证书认证问题的示例代码

标签:httpclients,SSL,HTTPS,安全认证证书,CloseableHttpClient,apache     发布时间:2018-01-14   

一、前言

这边基于apachehtmlunit包的httpclients模拟https访问,下面示例通过HttpClients.createDefault()方式创建CloseableHttpClient对象实例(取代用new DefaultHttpClient()实例化)解决了HTTPS安全证书认证问题。

二、示例说明

package test;@b@@b@import org.apache.http.HttpEntity;@b@import org.apache.http.HttpResponse;@b@import org.apache.http.client.methods.HttpPost;@b@import org.apache.http.entity.StringEntity;@b@import org.apache.http.impl.client.CloseableHttpClient;@b@import org.apache.http.impl.client.HttpClients;@b@import org.apache.http.util.EntityUtils;@b@@b@public class HttpSSLClientDemo {@b@@b@	    public static String postWithJSON() throws Exception {@b@	        HttpPost post = new HttpPost("https://127.0.0.1/api/order");@b@	        CloseableHttpClient client = HttpClients.createDefault();@b@	        String responseBody = null;//响应体@b@	        String param = "{\"orderId\":\"1343214\",\"uid\":\"123\"}";@b@	        StringEntity entity = new StringEntity(param,"utf-8");@b@	        entity.setContentEncoding("UTF-8");@b@	        entity.setContentType("application/json");@b@	        post.setEntity(entity);@b@@b@	        HttpResponse response = client.execute(post);@b@	        if(response.getStatusLine().getStatusCode() == 200) {@b@	            HttpEntity he = response.getEntity();@b@	            responseBody = EntityUtils.toString(he,"UTF-8");@b@	        }@b@	        return responseBody;@b@	    }@b@@b@	    public static void main(String[] args) throws Exception {@b@	        String result = postWithJSON();@b@	        System.out.println(result);@b@	    }@b@@b@}