Commit a525e8f8 authored by ZWT's avatar ZWT

nocommit

parent e8e478b5
package pps.core.auth;
/**
* 基础认证Auth
*
* @author ZWT
* @date 2023/01/09
*/
public interface Auth {
/**
* 基础认证Auth
*
* @return {@link String}
*/
String getAuth();
}
\ No newline at end of file
package pps.core.auth;
import org.apache.commons.codec.binary.Base64;
import java.nio.charset.StandardCharsets;
/**
* 用户名密码认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BasicAuth implements Auth {
private String username;
private String password;
public BasicAuth(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getAuth() {
String auth = String.format("%s:%s", this.username, this.password);
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
}
\ No newline at end of file
package pps.core.auth;
/**
* Bearer Token 认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BearerAuth implements Auth {
private String token;
public BearerAuth(String token) {
this.token = token;
}
@Override
public String getAuth() {
return "Bearer " + this.token;
}
}
\ No newline at end of file
package pps.core.auth;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* http请求客户端
*
* @author ZWT
* @date 2023/01/09
*/
@Slf4j
public class HttpRequestClient {
/**
* 默认连接超时(10s)
*/
private static final int DEFAULT_CONNECT_TIMEOUT = 30_000;
/**
* 默认读取超时(10s)
*/
private static final int DEFAULT_READ_TIMEOUT = 30_000;
/**
* 身份验证
*/
private Auth auth;
/**
* http客户端
*/
private HttpClient httpClient;
/**
* 用户名密码认证,默认的超时时间(10s)
*
* @param username 用户名
* @param password
* @param httpsFlag
*/
public HttpRequestClient(String username, String password, boolean httpsFlag) throws NoSuchAlgorithmException, KeyManagementException {
this(username, password,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
httpsFlag
);
}
/**
* 用户名密码认证,自定义超时时间
*
* @param username 用户名
* @param password
* @param connectTimeout
* @param readTimeout
* @param httpsFlag
*/
public HttpRequestClient(String username, String password, int connectTimeout, int readTimeout, boolean httpsFlag) throws NoSuchAlgorithmException, KeyManagementException {
this.auth = new BasicAuth(username, password);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout));
if (httpsFlag) {
httpClientBuilder.setSSLSocketFactory(this.createIgnoreVerifySSL());
}
this.httpClient = httpClientBuilder.build();
}
/**
* BearerToken 认证,默认的超时时间(10s)
*
* @param bearerToken
*/
public HttpRequestClient(String bearerToken) {
this(bearerToken,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT
);
}
/**
* BearerToken 认证,自定义超时时间
*
* @param bearerToken 不记名令牌
* @param connectTimeout 连接超时
* @param readTimeout 读取超时
*/
public HttpRequestClient(String bearerToken, int connectTimeout, int readTimeout) {
this.auth = new BearerAuth(bearerToken);
this.httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout))
.build();
}
/**
* 设置 HTTP 请求超时时间
*
* @param connectTimeout tcp 连接超时时间
* @param readTimeout 读取数据超时时间
* @return
*/
private RequestConfig getRequestConfig(int connectTimeout, int readTimeout) {
return RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(readTimeout)
.build();
}
/**
* 发送 GET 请求,不带参数
*
* @param url
* @return
*/
public String doGet(String url) {
return doGet(url, new HashMap<>());
}
/**
* 发送 GET 请求,不带参数
*
* @param uri
* @return
*/
public String doGet(URI uri) {
return doGet(uri, new HashMap<>());
}
/**
* 发送 GET 请求,K-V 形式参数
*
* @param url url
* @param params 参数个数
* @return {@link String}
*/
public String doGet(String url, Map<String, String> params) {
RequestBuilder reqBuilder = RequestBuilder.get(url);
return doGet(reqBuilder, params);
}
/**
* 发送 GET 请求,K-V 形式参数
*
* @param uri
* @param params
* @return
*/
public String doGet(URI uri, Map<String, String> params) {
RequestBuilder reqBuilder = RequestBuilder.get(uri);
return doGet(reqBuilder, params);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class
*
* @param url url
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(String url, Class<T> responseType) {
RequestBuilder reqBuilder = RequestBuilder.get(url);
return getForObject(reqBuilder, responseType);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class
*
* @param uri uri
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(URI uri, Class<T> responseType) {
RequestBuilder reqBuilder = RequestBuilder.get(uri);
return getForObject(reqBuilder, responseType);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class(需要认证)
*
* @param reqBuilder 构造器
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(RequestBuilder reqBuilder, Class<T> responseType) {
reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());
try {
HttpResponse resp = httpClient.execute(reqBuilder.build());
String result = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
return JSONUtil.toBean(result, responseType);
} catch (IOException e) {
log.error("getForObject 异常: reqBuilder={}, responseType={}", reqBuilder, responseType, e);
return null;
}
}
/**
* 发送 POST 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public String doPost(String url, String json) {
try {
HttpResponse resp = this.exchange(HttpMethod.POST, url, json);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doPost 异常: url={}, json={}", url, json, e);
return null;
}
}
/**
* 发送 POST 请求,x-www-form-urlencoded 形式
*
* @param url
* @param param 参数
* @return {@link String}
*/
public String doPostForm(String url, Map<String, Object> param) {
try {
HttpResponse resp = this.exchangeForm(url, param);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doPost form 异常: url={}", url, e);
return null;
}
}
/**
* 发送 POST 请求,JSON 形式,返回 HttpResponse
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doPostResp(String url, String json) {
return this.exchange(HttpMethod.POST, url, json);
}
/**
* 发送 PUT 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doPut(String url, String json) {
return this.exchange(HttpMethod.PUT, url, json);
}
/**
* 发送 PUT 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doDelete(String url, String json) {
return this.exchange(HttpMethod.DELETE, url, json);
}
/*---------------------------------------私有方法---------------------------------------*/
/**
* 发送请求POST x-www-form-urlencoded
*
* @param url
* @param param 参数
* @return {@link HttpResponse}
*/
private HttpResponse exchangeForm(String url, Map<String, Object> param) {
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, Object> entry : param.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
try {
String authString = auth.getAuth();
RequestBuilder reqBuilder = RequestBuilder.create(HttpMethod.POST.toString())
.setUri(url)
.addHeader(HttpHeaders.AUTHORIZATION, authString)
.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
log.info("exchangeForm,接口地址:{}", url);
log.info("exchangeForm,认证头:{} {}", HttpHeaders.AUTHORIZATION, authString);
log.info("exchangeForm,认证头:{} {}", "Content-Type", ContentType.APPLICATION_FORM_URLENCODED);
reqBuilder.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
return httpClient.execute(reqBuilder.build());
} catch (IOException e) {
log.error("doPost form 异常: url={}", url, e);
return null;
}
}
/**
* 发送请求
*
* @param method 方法
* @param url url
* @param json json
* @return {@link HttpResponse}
*/
private HttpResponse exchange(HttpMethod method, String url, String json) {
RequestBuilder reqBuilder = RequestBuilder.create(method.toString())
.setUri(url)
.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth())
.addHeader("Accept", ContentType.APPLICATION_JSON.toString())
.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
if (StringUtils.isNotBlank(json)) {
reqBuilder.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
}
try {
return httpClient.execute(reqBuilder.build());
} catch (IOException e) {
log.error("doPost 异常: url={}, json={}", url, json, e);
return null;
}
}
/**
* 发送get请求
*
* @param reqBuilder 构造器
* @param params 参数
* @return {@link String}
*/
private String doGet(RequestBuilder reqBuilder, Map<String, String> params) {
reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());
for (Map.Entry<String, String> entry : params.entrySet()) {
reqBuilder.addParameter(entry.getKey(), entry.getValue());
}
try {
HttpResponse resp = httpClient.execute(reqBuilder.build());
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doGet 异常: reqBuilder={}, params={}", reqBuilder, params, e);
return null;
}
}
/**
* 绕过SSL、TLS证书
*
* @return {@link SSLConnectionSocketFactory}
* @throws NoSuchAlgorithmException 没有这样算法异常
* @throws KeyManagementException 密钥管理例外
*/
private SSLConnectionSocketFactory createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
// 创建一个上下文(此处指定的协议类型似乎不是重点)
SSLContext ctx = SSLContext.getInstance("TLS");
// 创建一个跳过SSL证书的策略
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
// 使用上面的策略初始化上下文
ctx.init(null, new TrustManager[]{tm}, null);
// 创建一个包含各种SSL协议的SSLConnectionSocketFactory实例对象
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,
new String[]{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
return ssf;
}
}
package pps.core.common.cache;
import lombok.Data;
import xstartup.base.XContext;
import xstartup.cache.XCacheLife;
import xstartup.cache.XCacheObject;
import xstartup.cache.XSingleCache;
import java.util.Date;
/**
* 第三方Token查询缓存
*
* @author ZWT
* @date 2023/12/12
*/
@Data
public class ThirdPartyConfigCache implements XCacheObject, XCacheLife {
private String codeKey;
private String code;
private Integer validity;
private Date currentDate;
@Override
public Integer getDuration() {
return validity * 60;
}
@Override
public String getCacheKey() {
return this.codeKey;
}
/**
* 检查缓存是否存在指定的code
*
* @param context 上下文
* @param code 密码
* @return {@link ThirdPartyConfigCache}
*/
public static ThirdPartyConfigCache exist(XContext context, String code) {
return XSingleCache.get(Tool.class).find(context, code, ThirdPartyConfigCache.class);
}
/**
* 删去
*
* @param context 上下文
* @param loginName 登录名
*/
public static void delete(XContext context, String loginName) {
XSingleCache.get(Tool.class).delete(context, loginName, ThirdPartyConfigCache.class);
}
/**
* 设置缓存
*
* @param context 上下文
* @param cache 隐藏物
*/
public static void set(XContext context, ThirdPartyConfigCache cache) {
XSingleCache.get(Tool.class).set(context, cache);
}
static class Tool extends XSingleCache<ThirdPartyConfigCache> {
@Override
protected ThirdPartyConfigCache restore(XContext context, String cacheKey) {
return null;
}
}
}
\ No newline at end of file
package pps.core.prediction.constant;
/**
* 第三方接口地址
*
* @author ZWT
* @date 2024/03/18 09:25
*/
public class ThirdPartyApiConstant {
/*------------------------------ 长庆 ------------------------------*/
/**
* Redis缓存key
*/
public static final String CQ_TOKEN_CACHE_KEY = "pps.third.cq.token";
/**
* 长庆Token
*/
public static final String CQ_TOKEN = "/Smart_Well_Data/api/v1/Auth/GetToken";
/**
* 获取日耗电日产液等信息
*/
public static final String CQ_WELL_TECH_DAILY = "/Smart_Well_Data/api/v1/PvDataManagement/GET_WELL_TECH_DAILY";
/**
* 获取有功功率数据
*/
public static final String CQ_WELL_STATION_PV_DATA = "/Smart_Well_Data/api/v1/PvDataManagement/GET_WELL_STATION_PV_DATA";
/**
* 获取甘特图数据
*/
public static final String CQ_RPT_SYSTEM_START_STOP = "/Smart_Well_Data/api/v1/SdDataManagement/Get_RPT_SYSTEM_START_STOP";
/**
* 本日累计数据
*/
public static final String CQ_WELL_REAL_PV_DATA = "/Smart_Well_Data/api/v1/PvDataManagement/GET_WELL_Real_PV_DATA";
}
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