package com.neusoft.snet.app.thirdpart.api.util;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @Description http工具类
* @Author
*/
@Data
@Slf4j
public class HttpUtil {
/**
* GET请求--无参
*/
public static String doGet(String url, boolean proxy) {
log.info("请求地址:{} , 是否开启代理{}", url, proxy);
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
//单位毫秒
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();//设置请求的状态参数
try {
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpGet, setProxy(httpGet));
} else {
response = httpClient.execute(httpGet);
}
return response(httpClient, response);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* GET请求--有参
*/
public static String doGet(String url, Map<String, String> params, boolean proxy) {
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, "UTF-8"));
url = url + "?" + paramsStr;
HttpGet httpGet = new HttpGet(url);
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpGet, setProxy(httpGet));
} else {
response = httpClient.execute(httpGet);
}
return response(httpClient, response);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* GET请求--有参
* 有请求头
*/
public static String doGet(String url, JSONObject jsonObject, Map<String, String> params, boolean proxy) {
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
try {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(nvps, "UTF-8"));
url = url + "?" + paramsStr;
HttpGet httpGet = new HttpGet(url);
for (String str : jsonObject.keySet()) {
httpGet.setHeader(str, jsonObject.getString(str));
}
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpGet, setProxy(httpGet));
} else {
response = httpClient.execute(httpGet);
}
return response(httpClient, response);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* POST请求
*/
public static String doPost(String url, String params, boolean proxy) {
try {
log.info("请求地址:{} , 参数:{} , 是否开启代理:{}", url, params, proxy);
HttpPost httpPost = new HttpPost(url);
return getResponse(httpPost, params, proxy);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* POST请求
*
* @param url 请求地址
* @param jsonObject header参数
* @param params body参数
* @param proxy 代理开关
* @return
*/
public static String doPost(
String url,
JSONObject jsonObject,
String params,
boolean proxy
) {
try {
log.error("远程服务器!服务器地址{},请求头参数{},请求体参数{},是否开启代理{}",
url,
jsonObject,
params,
proxy);
HttpPost httpPost = new HttpPost(url);
return getResponse(httpPost, jsonObject, params, proxy);
} catch (Exception e) {
log.error("远程服务器异常!服务器地址{},请求头参数{},请求体参数{},是否开启代理{},异常内容{}",
url,
jsonObject,
params,
proxy,
e.getMessage());
return "";
}
}
/**
* POST请求
*/
public static String doPost(String url, String params, boolean proxy, boolean needSSL, Map<String, Object> sslParams) {
try {
log.error("远程服务器!服务器地址{}, 请求体参数{},是否开启代理{}, 是否需要SSL{},SSL参数{}",
url,
params,
proxy,
needSSL,
sslParams);
HttpPost httpPost = new HttpPost(url);
return getResponse(httpPost, params, proxy, needSSL, sslParams);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* doPut请求
*/
public static String doPut(String url, Map<String, String> headerMap, String requestBody, boolean proxy) {
String entityStr = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
//设置请求和传输超时时间
//单位毫秒
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000).setConnectTimeout(3000)
.setSocketTimeout(3000).build();//设置请求的状态参数
try {
HttpPut httpPut = new HttpPut(url);
httpPut.setConfig(requestConfig);
//添加头部信息
for (Map.Entry<String, String> header : headerMap.entrySet()) {
httpPut.addHeader(header.getKey(), header.getValue());
httpPut.addHeader("Content-Type", "application/json;charset=utf-8");
}
HttpEntity entity = new StringEntity(requestBody, "Utf-8");
log.info("请求体是:" + requestBody);
httpPut.setEntity(entity);
if (proxy) {
response = httpClient.execute(httpPut, setProxy(httpPut));
} else {
response = httpClient.execute(httpPut);
}
// 获得响应的实体对象
HttpEntity httpEntity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
entityStr = EntityUtils.toString(httpEntity, "UTF-8");
log.info("PUT请求路径:" + httpPut);
log.info("PUT请求结果:" + entityStr);
} catch (ClientProtocolException e) {
log.info("Http协议出现问题");
e.printStackTrace();
} catch (ParseException e) {
log.info("解析错误");
e.printStackTrace();
} catch (IOException e) {
log.info("IO异常");
e.printStackTrace();
} catch (MalformedChallengeException e) {
e.printStackTrace();
}
return entityStr;
}
/**
* 短信发送接口
*/
public static String doPost(String url, JSONObject header, JSONObject body, boolean proxy, int timeOut) {
try {
log.info("短信发送接口 地址:{},参数头:{},参数体:{},是否开启代理:{}, 超时时间:{}"
, url, header, body, proxy, timeOut);
HttpPost httpPost = new HttpPost(url);
return getResponse(httpPost, header, body, proxy, timeOut);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 短信发送
*/
private static String getResponse(HttpPost httpPost, JSONObject header, JSONObject body, boolean proxy, int timeOut) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();
httpPost.addHeader("Authorization", header.getString("Authorization"));
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
ByteArrayEntity entity = null;
try {
entity = new ByteArrayEntity(JSONObject.toJSONString(body).getBytes("UTF-8"));
entity.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
}
httpPost.setEntity(entity);
httpPost.setConfig(requestConfig);
log.info("请求信息:{}", httpPost);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpPost, setProxy(httpPost));
} else {
response = httpClient.execute(httpPost);
}
return response(httpClient, response);
}
private static String getResponse(HttpPost httpPost, String params, boolean proxy) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost = getHttpPost(httpPost, params);
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpPost, setProxy(httpPost));
} else {
response = httpClient.execute(httpPost);
}
return response(httpClient, response);
}
private static String getResponse(HttpPost httpPost, JSONObject jsonObject, String params, boolean proxy) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost = getHttpPost(httpPost, params);
httpPost.setConfig(requestConfig);
for (String str : jsonObject.keySet()) {
httpPost.setHeader(str, jsonObject.getString(str));
}
log.info("请求信息:{}" + httpPost);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpPost, setProxy(httpPost));
} else {
response = httpClient.execute(httpPost);
}
return response(httpClient, response);
}
private static String getResponse(HttpPost httpPost, String params, boolean proxy, boolean needSSL, Map<String, Object> sslParams) throws Exception {
CloseableHttpClient httpClient = null;
if (needSSL) {
String keyStoreStr = (String) sslParams.get("KEY_STORE");
String serverName = (String) sslParams.get("SERVER_NAME");
String basetruststoreName = (String) sslParams.get("BASETRUSTSTORE_NAME");
String pfxPwdStr = (String) sslParams.get("PFX_PWD");
String[] sslsfArr = (String[]) sslParams.get("SSL_SF");
KeyStore serverKeyStore = null;
KeyStore basetruststoreKeyStore = null;
InputStream serverIs = null;
InputStream basetruststoreIs = null;
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
serverKeyStore = KeyStore.getInstance(keyStoreStr);
serverIs = classLoader.getResourceAsStream(serverName);
serverKeyStore.load(serverIs, pfxPwdStr.toCharArray());
basetruststoreKeyStore = KeyStore.getInstance(keyStoreStr);
basetruststoreIs = classLoader.getResourceAsStream(basetruststoreName);
basetruststoreKeyStore.load(basetruststoreIs, pfxPwdStr.toCharArray());
} catch (KeyStoreException e) {
log.info("keyStore Load失败:", e);
} finally {
if (null != serverIs) {
serverIs.close();
}
if (null != basetruststoreIs) {
basetruststoreIs.close();
}
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(serverKeyStore, pfxPwdStr.toCharArray()).loadTrustMaterial(basetruststoreKeyStore, null).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext
, sslsfArr
, null
, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
log.info("获取携带证书 httpClient成功");
} else {
log.info("获取非携带证书 httpClient成功");
httpClient = HttpClients.createDefault();
}
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
httpPost = getHttpPost(httpPost, params);
httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
if (proxy) {
response = httpClient.execute(httpPost, setProxy(httpPost));
} else {
/* InputStream is = new ByteArrayInputStream(params.getBytes("UTF-8"));
InputStreamEntity inputStreamEntity = new InputStreamEntity(is, is.available());
httpPost.setEntity(inputStreamEntity);*/
response = httpClient.execute(httpPost);
}
return response(httpClient, response);
}
private static HttpPost getHttpPost(HttpPost httpPost, String params) throws UnsupportedEncodingException {
JSONObject jsonObject = JSONObject.parseObject(params);
if (jsonObject.containsKey("bearerToken")) {
httpPost.addHeader("Authorization", jsonObject.getString("bearerToken"));
jsonObject.remove("bearerToken");
params = JSONObject.toJSONString(jsonObject);
} else if (jsonObject.containsKey("header")) {
if ("onlineStore".equals(jsonObject.getString("header"))) {
httpPost.addHeader("version", jsonObject.getString("version"));
httpPost.addHeader("messageID", jsonObject.getString("messageID"));
httpPost.addHeader("custCode", jsonObject.getString("custCode"));
httpPost.addHeader("dateTimeStamp", jsonObject.getString("dateTimeStamp"));
jsonObject.remove("header");
jsonObject.remove("version");
jsonObject.remove("messageID");
jsonObject.remove("custCode");
jsonObject.remove("dateTimeStamp");
if (jsonObject.containsKey("token")) {
httpPost.addHeader("token", jsonObject.getString("token"));
jsonObject.remove("token");
httpPost.addHeader("encryptType", jsonObject.getString("encryptType"));
jsonObject.remove("encryptType");
}
} else if ("mobile".equals(jsonObject.getString("header"))) {
httpPost.addHeader("accessToken", jsonObject.getString("accessToken"));
httpPost.addHeader("requestId", jsonObject.getString("requestId"));
jsonObject.remove("accessToken");
jsonObject.remove("requestId");
}
}
if (jsonObject.containsKey("formData")) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
jsonObject.remove("formData");
if (jsonObject != null) {
for (String key : jsonObject.keySet()) {
builder.addPart(key,
new StringBody(jsonObject.getString(key), ContentType.create("text/plain", Consts.UTF_8)));
}
}
HttpEntity reqEntity = builder.build();
httpPost.setEntity(reqEntity);
} else {
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setEntity(new StringEntity(params, "UTF-8"));
}
log.info("请求params:{}", params);
return httpPost;
}
private static String response(CloseableHttpClient httpClient, CloseableHttpResponse response) throws IOException {
try {
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
log.info("返回应答:{}", jsonString);
return jsonString;
} else {
String jsonString = EntityUtils.toString(response.getEntity());
log.error("请求返回的数据:{}", jsonString);
}
} finally {
// 释放资源
if (httpClient != null) {
httpClient.close();
}
if (response != null) {
response.close();
}
}
return "";
}
/**
* 设置代理
*/
private static HttpClientContext setProxy(HttpRequestBase httpRequestBase) throws MalformedChallengeException {
HttpHost proxy = new HttpHost("192.168.0.1", 8080);
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
httpRequestBase.setConfig(config);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(proxy),
new UsernamePasswordCredentials("xxxx", "xxxx")
);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
return context;
}
}
httpclient请求公共类
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 本文与网络请求框架那篇文章大致类似,但封装的更为完善,介绍的也更详细,在项目中所有用到的网络请求都需要该类参与。 ...
- 在HttpClient的使用过程中,难免会遇到请求的传输协议为Https,而https与http的区别在上一篇文章...
- java可以通过Apache HttpClient请求接口数据Apache HttpClient maven ja...
- 紧接上一节,本节记录 【为GET和POST请求添加请求参数和请求头】我们平常浏览各个网站时,不免有时候就需要填写一...
- 在项目中可能会遇到这样的需求,我们在进行网络请求时,可能会遇到各种超时或者连接不上的情况。为了方便排查问题是出在前...