前言
最近公司做了一组使用https协议证书加密的接口,为了能够使用户比较容易的使用这套接口,于是乎做了一个访问的例子程序。本文记录一下这个例子程序。
DefaultHttpClient deprecated
https的访问使用了Apache HttpComponents工具,在网上一些早一些版本的例子中使用了DefaultHttpClient类来创建请求。但是在4.3版本以后DefaultHttpClient类已经不推荐使用了,于是本例子改用CloseableHttpClient类来创建请求。
DefaultHttpClient的官方API说明
Deprecated.
(4.3) use HttpClientBuilder see also CloseableHttpClient.
例子
直接上代码很简单的程序
maven引入包
org.apache.httpcomponents httpclient 4.5.3
测试代码
package pub.lichao.test.controller;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.message.BasicHeader;import org.apache.http.util.EntityUtils;/** * 利用HttpClient进行post请求 */public class HttpClientUtil { /** * 发送post请求 * @param url 资源的url * @param jsonstr json格式入参 * @param charset 编码方式 * @return */ public static String doPost(String url,String jsonstr,String charset){ String result = null; try{ //创建CloseableHttpClient类 HttpClient httpClient = HttpClientBuilder.create().build(); //创建post请求类 HttpPost httpPost = new HttpPost(url); //增加支持json的http头信息 httpPost.addHeader("Content-Type", "application/json"); StringEntity se = new StringEntity(jsonstr); se.setContentType("text/json"); se.setContentEncoding(new BasicHeader("Content-Type", "application/json")); httpPost.setEntity(se); //创建response请求 HttpResponse response = httpClient.execute(httpPost); if(response != null){ HttpEntity resEntity = response.getEntity(); if(resEntity != null){ //结果转换成string类型 result = EntityUtils.toString(resEntity,charset); } } }catch(Exception e){ e.printStackTrace(); } return result; } /** * 测试方法 * @param args */ public static void main(String[] args){ String url = "https://openapi.puliantongxun.com/v1/get_token"; String jsonStr = "{\"appId\":\"username\",\"appSecret\":\"secret\"}"; String httpOrgCreateTestRtn = doPost(url, jsonStr, "utf-8"); System.out.println("https result is :" + httpOrgCreateTestRtn); }}