package com.sdyy.common.httpcon;
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.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import java.security.NoSuchAlgorithmException;
/**
*
* * @className: HttpConnectionManager
*
* @description TODO
* * @param
* * @return
* * @throws
* * @author lizz
* * @date 2020 02 17 21:57
*
*/
@Component
public class HttpConnectionManager {
PoolingHttpClientConnectionManager cm = null;
@PostConstruct
public void init() {
LayeredConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
cm =new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
}
public CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
/*CloseableHttpClient httpClient = HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接*/
return httpClient;
}
}
package com.sdyy.common.httpcon;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdyy.common.utils.ByteUtils;
import com.sdyy.common.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
/**
*
* * @className: httpClient
*
* @description TODO
* * @param
* * @return
* * @throws
* * @author lizz
* * @date 2020 02 17 22:09
*
*/
@Log4j
@Component
public class httpClient {
@Autowired
HttpConnectionManager connManager;
/**
* @Description:post (json)
* @Author: lizz
* @Date: 2020/2/17 22:17
**/
public String httpPost(String url, JSONObject jsonParam) {
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpPost httpPost = new HttpPost(url);
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
String json=null;
CloseableHttpResponse response=null;
try {
response = httpClient.execute(httpPost);
InputStream in=response.getEntity().getContent();
json= IOUtils.toString(in);
in.close();
} catch (UnsupportedOperationException e) {
log.error("调用失败:"+e);
} catch (IOException e) {
log.error("调用失败:"+e);
}finally {
if(response!=null){
try {
response.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return json;
}
/**
* @Description:get
* @Author: lizz
* @Date: 2020/2/17 22:20
**/
public String httpGet(String url) {
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpGet httpget = new HttpGet(url);
String json=null;
CloseableHttpResponse response=null;
try {
response = httpClient.execute(httpget);
InputStream in=response.getEntity().getContent();
json= IOUtils.toString(in);
in.close();
} catch (UnsupportedOperationException e) {
log.error("调用失败:"+e);
} catch (IOException e) {
log.error("调用失败:"+e);
}finally {
if(response!=null){
try {
response.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return json;
}
public String httpGet_s(String url, Map headerMap, HttpServletResponse response, String retContentType) {
// get请求返回结果
String stringResult = null;
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse httpResponse=null;
try {
httpClient = HttpClients.createDefault();
setHeader_Get(httpget, headerMap);
httpResponse = httpClient.execute(httpget);
// 请求发送成功,并得到响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = httpResponse.getEntity();
/***
* 2018.11.29 add by yangyang get方法的返回类型可能为二进制流型,在这里进行判断
*/
if (StringUtils.isEmpty(retContentType)) {
stringResult = EntityUtils.toString(entity, "utf-8");
} else {
try {
byte[] responseBytes = ByteUtils.getData(entity);
retContentType = retContentType.replace("#", "/");
// response.setContentType("image/jpg");
// response.setContentType("application/octet-stream");
// //设置返回的文件类型
// response.setContentType("multipart/form-data");
// response.setContentType("application/vnd.ms-excel");
// response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setContentType(retContentType);
OutputStream os = response.getOutputStream();
os.write(responseBytes);
os.flush();
os.close();
} catch (Exception e) {
log.error("流类型接口返回错误: " + e.getMessage());
}
}
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
} finally {
if(response!=null){
try {
httpResponse.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return stringResult;
}
public String httpPost_s(String url, JSONObject jsonParam, Map headerMap) {
// post请求返回结果
String stringResult = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
/* System.out.println("___jsonParam___" + jsonParam);
System.out.println("___headerMap___" + headerMap);*/
httpClient = HttpClients.createDefault();
setHeader_Post(httpPost, headerMap);
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
stringResult = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
} finally {
if(httpResponse!=null){
try {
httpResponse.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return stringResult;
}
public String httpPost_s(String url, String strParam, Map headerMap) {
// post请求返回结果
String stringResult = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpClient = HttpClients.createDefault();
setHeader_Post(httpPost, headerMap);
if (null != strParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
stringResult = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
} finally {
if(httpResponse!=null){
try {
httpResponse.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return stringResult;
}
public String httpPost_x_s(String url, String strParam, Map headerMap) {
// post请求返回结果
String stringResult = null;
CloseableHttpResponse httpResponse = null;
CloseableHttpClient httpClient=connManager.getHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpClient = HttpClients.createDefault();
setHeader_Post(httpPost, headerMap);
if (null != strParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(strParam, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
stringResult = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
} finally {
if(httpResponse!=null){
try {
httpResponse.close();
} catch (IOException e) {
log.error("调用失败:"+e);
}
}
}
return stringResult;
}
private static void setHeader_Get(HttpGet request, Map headerMap) {
if (!MapUtils.isEmpty(headerMap)) {
Iterator entries = headerMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
request.setHeader(key, value);
}
}
}
private static void setHeader_Post(HttpPost request, Map headerMap) {
if (!MapUtils.isEmpty(headerMap)) {
Iterator entries = headerMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
request.setHeader(key, value);
}
}
}
}
转载:https://blog.csdn.net/qq_22041375/article/details/104521289
查看评论