【Java】HttpClient访问Restful Api(Https)

 

使用该工具类(HttpsUtils)可直接调用SSL API访问,如果为Http方式访问请查看我另一篇博文,后面还有更多Java相关知识,请关注我的CSDN博客互相学习。。,有什么问题也可以加我QQ:444623631,互相讨论。

 

package com.smart.mvc.util;

 


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class HttpsUtils {
private static PoolingHttpClientConnectionManager connMgr;
private static RequestConfig requestConfig;
private static final int MAX_TIMEOUT = 7000;


static {
// 设置连接池
connMgr = new PoolingHttpClientConnectionManager();
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());


RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}


/**
* 创建SSL安全连接

* @return
*/
@SuppressWarnings("deprecation")
private static CloseableHttpClient createSSLClientDefault() {
SSLContextBuilder builder = new SSLContextBuilder();
CloseableHttpClient httpclient = null;
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
NoopHostnameVerifier.INSTANCE);
Registry registry = RegistryBuilder.create()
.register("http", new PlainConnectionSocketFactory()).register("https", sslConnectionSocketFactory)
.build();


PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(100);
httpclient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).setConnectionManager(cm)
.build();
} catch (Exception e) {
// TODO: handle exception
}
return httpclient;
}


/**
* 发送GET请求,无参

* @param tokenId X-Auth-Token的请求头
* @param url
* @return
*/
public static String doGet(String tokenId, String url) {
Map header = new HashMap<>();
header.put("X-Auth-Token", tokenId);
return doGet(header, url, new HashMap());
}


/**
* 发送GET请求,参数为Key-Value形式

* @param headers 请求头
* @param url 地址
* @param params 参数
* @return
*/
public static String doGet(Map headers, String url, Map params) {
String apiUrl = url;
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : params.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
String result = null;


try {
HttpGet httpGet = new HttpGet(apiUrl);
for (Map.Entry entry : headers.entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
httpGet.setConfig(requestConfig);
HttpResponse response = createSSLClientDefault().execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();


System.out.println("执行状态码 : " + statusCode);


HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}


/**
* 发送POST,参数为Key-Value形式

* @param headers 请求头
* @param apiUrl 地址
* @param params 参数
* @return
*/
public static String doPost(Map headers, String apiUrl, Map params) {
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;


try {
for (Map.Entry entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
httpPost.setConfig(requestConfig);
List pairList = new ArrayList(params.size());
for (Map.Entry entry : params.entrySet()) {
NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = createSSLClientDefault().execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}

/**
* 发送 Post请求,参数为Json格式
* @param apiUrl
* @param json
* @return
*/
public static String doPost(String apiUrl, String json) {
return doPost(new HashMap<>(), apiUrl, json);
}


/**
* 发送POST请求,参数JSON格式

* @param headers 请求头
* @param apiUrl 地址
* @param json 参数
* @return
*/
public static String doPost(Map headers, String apiUrl, String json) {
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
String httpStr = null;


try {
for(Map.Entry entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json, "UTF-8");// 解决中文乱码问题
// stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = createSSLClientDefault().execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
httpStr = EntityUtils.toString(entity, "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
}

 

你可能感兴趣的:(Java)