一、前言
这边基于apache的htmlunit包的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@}