public class HttpUtil {
public static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
public static final ContentType TEXT_PLAIN = ContentType.create("text/plain", StandardCharsets.UTF_8);
private static int connectTimeout = 15000;
private static int readTimeout = 60000;
/**
* HttpClient 连接池
*/
private static PoolingHttpClientConnectionManager cm = null;
static {
// 初始化连接池,可用于请求HTTP/HTTPS(信任所有证书)
cm = new PoolingHttpClientConnectionManager(getRegistry());
// 整个连接池最大连接数
cm.setMaxTotal(200);
// 每路由最大连接数,默认值是2
cm.setDefaultMaxPerRoute(5);
}
/**
* 发送 HTTP GET请求
* <p>不带请求参数和请求头</p>
*
* @param url 地址
* @return
* @throws Exception
*/
public static String httpGet(String url) throws Exception {
HttpGet httpGet = new HttpGet(url);
return doHttp(httpGet);
}
/**
* 发送 HTTP GET请求
* <p>带请求参数,不带请求头</p>
*
* @param url 地址
* @param params 参数
* @return
* @throws Exception
* @throws Exception
*/
public static String httpGet(String url, Map<String, Object> params) throws Exception {
// 转换请求参数
List<NameValuePair> pairs = covertParams2NVPS(params);
// 装载请求地址和参数
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
return doHttp(httpGet);
}
/**
* 发送 HTTP GET请求
* <p>带请求参数和请求头</p>
*
* @param url 地址
* @param headers 请求头
* @param params 参数
* @return
* @throws Exception
* @throws Exception
*/
public static String httpGet(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
// 转换请求参数
List<NameValuePair> pairs = covertParams2NVPS(params);
// 装载请求地址和参数
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ub.setParameters(pairs);
HttpGet httpGet = new HttpGet(ub.build());
// 设置请求头
for (Map.Entry<String, Object> param : headers.entrySet())
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
return doHttp(httpGet);
}
public static Map<String, Object> httpGetSVC(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {
// 转换请求参数
List<NameValuePair> pairs = covertParams2NVPS(params);
// 装载请求地址和参数
URIBuilder ub = new URIBuilder();
ub.setPath(url);
ub.setParameters(pairs);
URI ub2 = ub.build();
if ("/".equals(ub.toString().substring(0, 1))) {
ub2 = new URI(ub.toString().substring(1));
}
HttpGet httpGet = new HttpGet(ub2);
// 设置请求头
for (Map.Entry<String, Object> param : headers.entrySet())
httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
return doHttpSVC(httpGet);
}
/**
* 发送 HTTP POST请求
* <p>不带请求参数和请求头</p>
*
* @param url 地址
* @return
* @throws Exception
*/
public static String httpPost(String url,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
return doHttp(httpPost);
}
/**
* 发送 HTTP POST请求
* <p>带请求参数,不带请求头</p>
*
* @param url 地址
* @param params 参数
* @return
* @throws Exception
*/
public static String httpPost(String url, Map<String, Object> params,String proxyFlag) throws Exception {
// 转换请求参数
List<NameValuePair> pairs = covertParams2NVPS(params);
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求参数
httpPost.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}
/**
* 发送 HTTP POST请求
* <p>带请求参数和请求头</p>
*
* @param url 地址
* @param headers 请求头
* @param params 参数
* @return
* @throws Exception
*/
public static String httpPost(String url, Map<String, Object> headers, Map<String, Object> params,String proxyFlag) throws Exception {
// 转换请求参数
List<NameValuePair> pairs = covertParams2NVPS(params);
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求参数
httpPost.setEntity(new UrlEncodedFormEntity(pairs, StandardCharsets.UTF_8.name()));
// 设置请求头
for (Map.Entry<String, Object> param : headers.entrySet())
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
return doHttp(httpPost);
}
/**
* 发送HTTP POST/FORM请求
* <p>模拟表单文件上传,默认表单名称为“media”,无附加表单</p>
*
* @param url 请求地址
* @param pathName 模拟表单文件全路径名
* @return Http POST/FORM 请求结果
* @throws Exception IO流异常
*/
public static String httpPostForm(String url, String pathName,String proxyFlag) throws Exception {
return httpPostForm(url, "media", pathName, Maps.newHashMap(),proxyFlag);
}
/**
* 发送HTTP POST/FORM请求
* <p>模拟表单文件上传,默认表单名称为“media”,无附加表单</p>
*
* @param url 请求地址
* @param file 模拟表单文件
* @return Http POST/FORM 请求结果
* @throws Exception IO流异常
*/
public static String httpPostForm(String url, File file,String proxyFlag) throws Exception {
return httpPostForm(url, "media", file, Maps.newHashMap(),proxyFlag);
}
/**
* 发送 HTTP POST/FORM请求
* <p>模拟表单文件上传</p>
*
* @param url 请求地址
* @param name 模拟表单名称
* @param pathName 模拟表单文件路径
* @param map 文件上传表单之外的附加表单,新增永久视频素材API需要使用该字段
* @return Http POST/FORM 请求结果
* @throws Exception IO流异常
*/
public static String httpPostForm(String url, String name, String pathName, Map<String, Object> map,String proxyFlag) throws Exception {
File file = new File(pathName);
// 检查文件名是否合法,以及文件是否存在
if (!file.isFile() || !file.exists())
throw new Exception("HttpClient Post/Form模拟表单请求的文件名不合法或文件不存在");
return httpPostForm(url, name, file, map,proxyFlag);
}
/**
* 发送 HTTP POST/FORM请求
* <p>模拟表单文件上传</p>
*
* @param url 请求地址
* @param name 模拟表单名称
* @param file 模拟表单文件
* @param map 文件上传表单之外的附加表单,新增永久视频素材API需要使用该字段
* @return Http POST/FORM 请求结果
* @throws Exception IO流异常
*/
public static String httpPostForm(String url, String name, File file, Map<String, Object> map,String proxyFlag) throws Exception {
// 初始化请求链接
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 组装模拟表单
FileBody body = new FileBody(file);
// 组装HTTP表单请求参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart(name, body);
// 附加表单
if (MapUtils.isNotEmpty(map)) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() == null)
continue;
builder.addTextBody(entry.getKey(), entry.getValue().toString(), TEXT_PLAIN);
}
}
// 构建HttpEntity
HttpEntity entity = builder.build();
// 设置请求参数
httpPost.setEntity(entity);
return doHttp(httpPost);
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String httpPostJson(String url, Map<String, Object> headers, String param,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
// 设置请求头
for (Map.Entry<String, Object> params : headers.entrySet())
httpPost.addHeader(params.getKey(), String.valueOf(params.getValue()));
return doHttp(httpPost);
}
public static Map<String, Object> httpPostJsonSVC(String url, Map<String, Object> headers, String param,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
// 设置请求头
for (Map.Entry<String, Object> params : headers.entrySet())
httpPost.addHeader(params.getKey(), String.valueOf(params.getValue()));
return doHttpSVC(httpPost);
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String httpPostJson(String url, String param,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}
public static String httpPostJson(String url, String param,Map<String, Object> headers,String proxyFlag)throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
for (Map.Entry<String, Object> params : headers.entrySet()) {
httpPost.addHeader(params.getKey(), String.valueOf(params.getValue()));
}
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static <T> T httpPostJson(String url, JSONObject param,Class<T> clazz,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
//设置请求超时
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param.toString(), StandardCharsets.UTF_8.name()));
String result = doHttp(httpPost);
JSONObject jsonObject=JSONObject.parseObject(result);
T t = JSONObject.toJavaObject(jsonObject, clazz);
return t;
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static <T> T httpPostJson(String url, JSONObject param, Map<String, Object> headers,Class<T> clazz,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
//设置请求超时
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
for (Map.Entry<String, Object> params : headers.entrySet())
httpPost.addHeader(params.getKey(), String.valueOf(params.getValue()));
// 设置请求参数
httpPost.setEntity(new StringEntity(param.toString(), StandardCharsets.UTF_8.name()));
String result = doHttp(httpPost);
JSONObject jsonObject=JSONObject.parseObject(result);
T t = JSONObject.toJavaObject(jsonObject, clazz);
return t;
}
/**
* 发送 HTTP POST请求,参数格式XML
* <p>请求参数是XML格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String httpPostXml(String url, String param,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求头
httpPost.addHeader("Content-Type", "application/xml; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}
/**
* 发送post请求(json)
* @param url
* @param paramJson
* @param headers
* @return
*/
public static String httpPostJson(String url, String paramJson,Map<String, Object> headers) {
HttpClient httpClient;
HttpPost postMethod;
HttpResponse response;
String reponseContent = null;
try {
httpClient = HttpClients.createDefault();
postMethod = new HttpPost(url);
//设置请求头
postMethod.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
postMethod.setEntity(new StringEntity(paramJson, StandardCharsets.UTF_8.name()));
// 设置请求头
for (Map.Entry<String, Object> params : headers.entrySet()) {
postMethod.addHeader(params.getKey(), String.valueOf(params.getValue()));
}
response = httpClient.execute(postMethod);
HttpEntity httpEntity = response.getEntity();
reponseContent = EntityUtils.toString(httpEntity);
EntityUtils.consume(httpEntity);
} catch (Exception e) {
log.error("发送POST请求异常",e);
}
return reponseContent;
}
/**
* 发送 HTTPS POST请求
* <p>使用指定的证书文件及密码,不带请求头信息</p>
*
* @param url
* @param param
* @param path
* @param password
* @return
* @throws Exception
* @throws Exception
*/
public static String httpsPost(String url, String param, String path, String password,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttps(httpPost, path, password);
}
/**
* 发送 HTTPS POST请求
* <p>使用指定的证书文件及密码,请求头为“application/xml;charset=UTF-8”</p>
*
* @param url
* @param param
* @param path
* @param password
* @return
* @throws Exception
* @throws Exception
*/
public static String httpsPostXml(String url, String param, String path, String password,String proxyFlag) throws Exception {
HttpPost httpPost = getHttpPost(url,proxyFlag);
// 设置请求头
httpPost.addHeader("Content-Type", "application/xml; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttps(httpPost, path, password);
}
/**
* 将Map键值对拼接成QueryString字符串,UTF-8编码
*
* @param params
* @return
* @throws Exception
*/
public static String getQueryStr(Map<String, Object> params) throws Exception {
return URLEncodedUtils.format(covertParams2NVPS(params), StandardCharsets.UTF_8.name());
}
/**
* 将JavaBean属性拼接成QueryString字符串,UTF-8编码
*
* @param bean
* @return
* @throws Exception
*/
public static String getQueryStr(Object bean) throws Exception {
// 将JavaBean转换为Map
Map<String, Object> map = PropertyUtils.describe(bean);
// 移除Map中键为“class”和值为空的项
map = Maps.filterEntries(map, new Predicate<Map.Entry<String, Object>>() {
public boolean apply(Map.Entry<String, Object> input) {
// 返回false表示排除该项
return !(input.getKey().equals("class") || input.getValue() == null);
}
});
return URLEncodedUtils.format(covertParams2NVPS(map), StandardCharsets.UTF_8.name());
}
/**
* 将表单字符串转换为JavaBean
*
* @param queryStr 表单字符串
* @param clazz {@link Class}待转换的JavaBean
* @return
* @throws Exception
*/
public static <T> T parseNVPS2Bean(String queryStr, Class<T> clazz) throws Exception {
// 将“表单字符串”形式的字符串解析成NameValuePair集合
List<NameValuePair> list = URLEncodedUtils.parse(queryStr, StandardCharsets.UTF_8);
Map<String, String> rsMap = Maps.newHashMap();
// 将NameValuePair集合中的参数装载到Map中
for (NameValuePair nvp : list)
rsMap.put(nvp.getName(), nvp.getValue());
// 实例化JavaBean对象
T t = clazz.newInstance();
// 将Map键值对装载到JavaBean中
BeanUtils.populate(t, rsMap);
return t;
}
/**
* 转换请求参数,将Map键值对拼接成QueryString字符串
*
* @param params
* @return
*/
public static String covertParams2QueryStr(Map<String, Object> params) {
List<NameValuePair> pairs = covertParams2NVPS(params);
return URLEncodedUtils.format(pairs, StandardCharsets.UTF_8.name());
}
/**
* 转换请求参数
*
* @param params
* @return
*/
public static List<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> param : params.entrySet())
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
return pairs;
}
public static String httpsPostJson(String url, String param) throws Exception{
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(url);
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
//设置请求头
httpPost.addHeader("Content-Type","application/json; charset=UTF-8");
try {
CloseableHttpResponse response = client.execute(httpPost);
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
//WorksheetNtWeb worksheetNtWeb = JSON.parseObject(body, WorksheetNtWeb.class);
return body;
}
//JSON映射到实体
//释放链接
response.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
log.error("https请求失败", e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("https请求失败", e);
}
return "";
}
public static String httpsPostJson(String url, Map<String, Object> headers,String param) throws Exception{
String body = "";
//采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
//创建自定义的httpclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
HttpPost httpPost = new HttpPost(url);
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
//设置请求头
httpPost.addHeader("Content-Type","application/json; charset=UTF-8");
// 设置请求头
for (Map.Entry<String, Object> params : headers.entrySet())
httpPost.addHeader(params.getKey(), String.valueOf(params.getValue()));
try {
CloseableHttpResponse response = client.execute(httpPost);
org.apache.http.HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "utf-8");
//WorksheetNtWeb worksheetNtWeb = JSON.parseObject(body, WorksheetNtWeb.class);
return body;
}
//JSON映射到实体
//释放链接
response.close();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
log.error("https请求失败", e);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("https请求失败", e);
}
return "";
}
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3");
// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
}
/**
* 发送 HTTP 请求
*
* @param request
* @return
* @throws Exception
*/
private static String doHttp(HttpRequestBase request) throws Exception {
// 通过连接池获取连接对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
return doRequest(httpClient, request);
}
private static Map<String, Object> doHttpSVC(HttpRequestBase request) throws Exception {
// 通过连接池获取连接对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
return doRequestSVC(httpClient, request);
}
/**
* 发送 HTTPS 请求
* <p>使用指定的证书文件及密码</p>
*
* @param request
* @param path
* @param password
* @return
* @throws Exception
* @throws Exception
*/
private static String doHttps(HttpRequestBase request, String path, String password) throws Exception {
// 获取HTTPS SSL证书
SSLConnectionSocketFactory csf = getSSLFactory(path, password);
// 通过连接池获取连接对象
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
return doRequest(httpClient, request);
}
/**
* 获取HTTPS SSL连接工厂
* <p>使用指定的证书文件及密码</p>
*
* @param path 证书全路径
* @param password 证书密码
* @return
* @throws Exception
* @throws Exception
*/
private static SSLConnectionSocketFactory getSSLFactory(String path, String password) throws Exception {
// 初始化证书,指定证书类型为“PKCS12”
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// 读取指定路径的证书
FileInputStream input = new FileInputStream(new File(path));
try {
// 装载读取到的证书,并指定证书密码
keyStore.load(input, password.toCharArray());
} finally {
input.close();
}
// 获取HTTPS SSL证书连接上下文
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
// 获取HTTPS连接工厂,指定TSL版本
SSLConnectionSocketFactory sslCsf = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
return sslCsf;
}
/**
* 获取HTTPS SSL连接工厂
* <p>跳过证书校验,即信任所有证书</p>
*
* @return
* @throws Exception
*/
private static SSLConnectionSocketFactory getSSLFactory() throws Exception {
// 设置HTTPS SSL证书信息,跳过证书校验,即信任所有证书请求HTTPS
SSLContextBuilder sslBuilder = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
// 获取HTTPS SSL证书连接上下文
SSLContext sslContext = sslBuilder.build();
// 获取HTTPS连接工厂
SSLConnectionSocketFactory sslCsf = new SSLConnectionSocketFactory(sslContext, new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
return sslCsf;
}
/**
* 获取 HTTPClient注册器
*
* @return
* @throws Exception
*/
private static Registry<ConnectionSocketFactory> getRegistry() {
Registry<ConnectionSocketFactory> registry = null;
try {
registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()).register("https", getSSLFactory()).build();
} catch (Exception e) {
log.error("获取 HTTPClient注册器失败", e);
}
return registry;
}
/**
* 处理Http/Https请求,并返回请求结果
* <p>注:默认请求编码方式 UTF-8</p>
*
* @param httpClient
* @param request
* @return
* @throws Exception
*/
private static String doRequest(CloseableHttpClient httpClient, HttpRequestBase request) throws Exception {
String result = null;
CloseableHttpResponse response = null;
try {
// 获取请求结果
response = httpClient.execute(request);
// 解析请求结果
HttpEntity entity = response.getEntity();
// 转换结果
result = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
// 关闭IO流
EntityUtils.consume(entity);
} finally {
if (null != response)
response.close();
}
return result;
}
private static Map<String, Object> doRequestSVC(CloseableHttpClient httpClient, HttpRequestBase request) throws Exception {
Map<String, Object> result = Maps.newConcurrentMap();
String responseJson = null;
CloseableHttpResponse response = null;
try {
// 获取请求结果
response = httpClient.execute(request);
// 解析请求结果
HttpEntity entity = response.getEntity();
result.put("JF_SN", response.getFirstHeader("JF_SN").getValue() != null ? response.getFirstHeader("JF_SN").getValue() : null);
result.put("JF_RTF", response.getFirstHeader("JF_RTF").getValue() != null ? response.getFirstHeader("JF_RTF").getValue() : null);
// 转换结果
responseJson = EntityUtils.toString(entity, StandardCharsets.UTF_8.name());
result.put("response", responseJson);
// 关闭IO流
EntityUtils.consume(entity);
} finally {
if (null != response)
response.close();
}
return result;
}
private static HttpPost getHttpPost(String url,String proxyFlag) {
HttpPost httpPost = new HttpPost(url);
String proxyStr = findProxySettingsLiunx();
RequestConfig requestConfig = null;
if("Y".equals(proxyFlag)&&!StringUtils.isEmpty(proxyStr)) {
log.info("http请求有代理",JSON.toJSONString(requestConfig));
String[] proxyArr = proxyStr.split(":");
HttpHost proxy=new HttpHost(proxyArr[0],Integer.parseInt(proxyArr[1]),"http");
requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setProxy(proxy)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
}else {
log.info("http请求无代理",JSON.toJSONString(requestConfig));
requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
}
log.info("http请求配置详情:[{}]",JSON.toJSONString(requestConfig));
httpPost.setConfig(requestConfig);
return httpPost;
}
/**
* 获取当前系统的代理设置
* <p>注:默认请求编码方式 UTF-8</p>
*
* @return String
* @throws Exception
*/
private static String findProxySettings() {
try {
System.setProperty("java.net.useSystemProxies", "true");
List<Proxy> l = ProxySelector.getDefault().select(new URI("https://b2b.csair.com"));
for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
Proxy proxy = iter.next();
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
} else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
System.out.println("proxy getHostString : " + addr.getHostString());
return addr.getHostName()+":"+addr.getPort();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取当前系统的代理设置
* <p>注:默认请求编码方式 UTF-8</p>
*
* @return String
* @throws Exception
*/
private static String findProxySettingsLiunx() {
try {
Map<String, String> env = System.getenv();
String proxy = env.get("http_proxy");
if(!StringUtils.isEmpty(proxy)) {
return proxy.replace("http://", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
HttpPost httpPost = new HttpPost("http://10.79.4.90:8090/order/queryAllOrderByOrderno");
String proxyStr = "ecgproxy.csair.com:80";
RequestConfig requestConfig = null;
if("Y".equals("Y")&&!StringUtils.isEmpty(proxyStr)) {
log.info("http请求有代理",JSON.toJSONString(requestConfig));
String[] proxyArr = proxyStr.split(":");
HttpHost proxy=new HttpHost(proxyArr[0],Integer.parseInt(proxyArr[1]),"http");
requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setProxy(proxy)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
}else {
log.info("http请求无代理",JSON.toJSONString(requestConfig));
requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(readTimeout).setSocketTimeout(connectTimeout).build();
}
log.info("http请求配置详情:[{}]",JSON.toJSONString(requestConfig));
httpPost.setConfig(requestConfig);
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
*
* @param url
* @param param
* @return
* @throws Exception
*/
public static String httpPostJson(String url, String param) throws Exception {
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}
/**
* 发送 HTTP POST请求,参数格式JSON
* <p>请求参数是JSON格式,数据编码是UTF-8</p>
* @param url
* @param param
* @param timeOut 超时时间 单位为毫秒
* @return
* @throws Exception
*/
public static String httpPostJson(String url, String param,int timeOut) throws Exception {
System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(timeOut));
System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(timeOut));
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.addHeader("Content-Type", "application/json; charset=UTF-8");
// 设置请求参数
httpPost.setEntity(new StringEntity(param, StandardCharsets.UTF_8.name()));
return doHttp(httpPost);
}