Commit 9e0491c4 authored by KeYong's avatar KeYong

提价https远程调用代码

parent fbc9605e
......@@ -66,13 +66,11 @@ public class HttpContentTypeUtil {
//System.out.println("初始化HttpClientTest~~~开始");
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
// builder.build(), NoopHostnameVerifier.INSTANCE);
SSLContext ctx = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{ "TLSv1", "TLSv1.2" }, null, NoopHostnameVerifier.INSTANCE);
// 配置同时支持 HTTP 和 HTPPS
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
"https", sslsf).build();
"https", sslsf).register(
"http", PlainConnectionSocketFactory.getSocketFactory()).build();
// 初始化连接管理器
pool = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
......@@ -114,7 +112,6 @@ public class HttpContentTypeUtil {
* 发送Post请求
*/
private static String sendHttpPost(HttpPost httpPost) {
log.info("================httpPost信息: " + JSON.toJSONString(httpPost));
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
......@@ -129,8 +126,6 @@ public class HttpContentTypeUtil {
// 得到响应实例
HttpEntity entity = response.getEntity();
log.info("==========response=============" + JSON.toJSONString(response));
// 可以获得响应头
// Header[] headers = response.getHeaders(HttpHeaders.CONTENT_TYPE);
// for (Header header : headers) {
......@@ -146,6 +141,7 @@ public class HttpContentTypeUtil {
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
log.info("调用header:" + JSON.toJSONString(httpPost.getAllHeaders()) + ";\n调用body: " + JSON.toJSONString(httpPost.getEntity()) + ";\n调用返回:" + JSON.toJSONString(entity));
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() || HttpStatus.SC_CREATED == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
......@@ -612,8 +608,9 @@ public class HttpContentTypeUtil {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
httpPost.addHeader(entry.getKey(), entry.getValue());
}
log.info("请求头======================" + JSON.toJSONString(httpPost.getAllHeaders()));
// 设置参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
......@@ -621,6 +618,7 @@ public class HttpContentTypeUtil {
builder.addPart(key, new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity entity = builder.build();
log.info("请求体======================" + JSON.toJSONString(entity));
httpPost.setEntity(entity);
}
} catch (Exception e) {
......
package com.yeejoin.equipmanage.common.utils;
import com.alibaba.fastjson.JSON;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* @author keyong
* @title: HttpsGetAndPostUtil
* <pre>
* @description: TODO
* </pre>
* @date 2023/11/9 8:30
*/
public class HttpsGetAndPostUtil {
private final Logger logger = LoggerFactory.getLogger(HttpsGetAndPostUtil.class);
static CloseableHttpClient httpClient;
static CloseableHttpResponse httpResponse;
public static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
/**
* 发送https请求
*
* @throws Exception
*/
public static String sendByHttp(Map<String, String> headerMap, Map<String, String> params, String url) {
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
// 设置参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
if (params != null) {
for (String key: params.keySet()) {
builder.addPart(key, new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
}
// httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
httpClient = HttpsGetAndPostUtil.createSSLClientDefault();
httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
System.out.println("新方法返回结果=================" + JSON.toJSONString(httpEntity));
if (httpEntity != null) {
String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
return jsObject;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
httpResponse.close();
httpClient.close();
System.out.println("请求流关闭完成");
} catch (IOException e) {
System.out.println("请求流关闭出错");
e.printStackTrace();
}
}
}
}
......@@ -490,10 +490,9 @@ public class SyncDataServiceImpl implements ISyncDataService {
warnMap.put("warns", alarmList);
logger.info("开始调用平台服务存储告警数据warns:" + JSON.toJSONString(alarmList));
requestVo.setBody(warnMap);
logger.info("==============header:" + JSON.toJSONString(headerMap) + "; body: " + JSON.toJSONString(requestVo));
logger.info("===============告警存入header:" + JSON.toJSONString(headerMap) + ";\n==================告警存入body: " + JSON.toJSONString(requestVo));
String s = HttpContentTypeUtil.sendHttpPostJsonWithHeader(sendAlarmUrl, JSON.toJSONString(requestVo), headerMap);
logger.info("===============告警推送联调==================返回数据:" + s);
logger.info("===============告警推送联调返回数据:" + JSON.toJSONString(s));
}
} catch (Exception e) {
logger.error("equipAlarmDataSync告警数据发送接口请求异常:" + e.getMessage());
......
......@@ -4,9 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.common.datasync.vo.AppTokenVo;
import com.yeejoin.equipmanage.common.utils.HttpContentTypeUtil;
import com.yeejoin.equipmanage.common.utils.HttpsGetAndPostUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -73,11 +71,11 @@ public class DcsUtil {
map.put("client_secret", clientSecret);
String content;
if (isHttpsUrl(gettokenUrl)){
content = HttpsGetAndPostUtil.sendByHttp(headerMap, map, gettokenUrl);
content = HttpContentTypeUtil.sendHttpPostFormWithHeader(gettokenUrl, map, headerMap);
} else {
content = HttpContentTypeUtil.doPostForm(gettokenUrl, map);
}
logger.info("header:" + JSON.toJSONString(headerMap) + "; body: " + JSON.toJSONString(map) + "; 调用获取token返回:" + content);
if (StringUtils.isNotBlank(content)) {
AppTokenVo appTokenVo = JSONObject.parseObject(content, AppTokenVo.class);
// accessToken = String.join(" ", appTokenVo.getToken_type(), appTokenVo.getAccess_token());
......@@ -86,7 +84,7 @@ public class DcsUtil {
redisTemplate.opsForValue().set(tokenKey, accessToken, expiresIn);
}
}
logger.info("accessToken 是----------" + accessToken);
logger.info("accessToken 是=====================" + JSON.toJSONString(accessToken));
return accessToken;
}
......
......@@ -70,7 +70,7 @@ isSendApp=false
equip.report.url=/fire-fighting-system/ureport/preview?_u=file:
#?????????
dcs.send.message=true
dcs.send.message=false
dcs.client-id=fire_system
dcs.grant-type=client_credentials
dcs.scope=all
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment