方法调用工具类

yun-zuoyi
castle.zang 4 years ago
parent 66653ed536
commit f9332cd514

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>i3plus-pojo</artifactId>
<groupId>i3plus.pojo</groupId>
<version>1.0-DEV-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>i3plus-pojo-bsp</artifactId>
<dependencies>
<dependency>
<groupId>i3plus.pojo</groupId>
<artifactId>i3plus-pojo-base</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
<profiles>
<profile>
<id>dev</id>
<properties>
<profileActive>DEV</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profileActive>TEST</profileActive>
</properties>
</profile>
<profile>
<id>docker</id>
<properties>
<profileActive>DOCKER</profileActive>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<profileActive>PROD</profileActive>
</properties>
</profile>
</profiles>
<build>
<finalName>${project.artifactId}-${project.version}</finalName>
</build>
</project>

@ -0,0 +1,98 @@
package cn.estsh.i3plus.bspserver.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
/**
* @Description :
* @Reference :
* @Author : Castle
* @CreateDate : 2021/6/17 13:40
* @Modify:
**/
public class GsonTool {
private static Gson gson = null;
static {
gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
}
/**
* Object json
*
* @param src
* @return String
*/
public static String toJson(Object src) {
return gson.toJson(src);
}
/**
* json clsObject
*
* @param json
* @param classOfT
* @return
*/
public static <T> T fromJson(String json, Class<T> classOfT) {
return gson.fromJson(json, classOfT);
}
/**
* json rawClass<classOfT> Object
*
* @param json
* @param classOfT
* @param argClassOfT
* @return
*/
public static <T> T fromJson(String json, Class<T> classOfT, Class argClassOfT) {
Type type = new ParameterizedType4ReturnT(classOfT, new Class[]{argClassOfT});
return gson.fromJson(json, type);
}
public static class ParameterizedType4ReturnT implements ParameterizedType {
private final Class raw;
private final Type[] args;
public ParameterizedType4ReturnT(Class raw, Type[] args) {
this.raw = raw;
this.args = args != null ? args : new Type[0];
}
@Override
public Type[] getActualTypeArguments() {
return args;
}
@Override
public Type getRawType() {
return raw;
}
@Override
public Type getOwnerType() {
return null;
}
}
/**
* json clslist
*
* @param json
* @param classOfT
* @return
*/
public static <T> List<T> fromJsonList(String json, Class<T> classOfT) {
return gson.fromJson(
json,
new TypeToken<List<T>>() {
}.getType()
);
}
}

@ -0,0 +1,157 @@
package cn.estsh.i3plus.bspserver.util;
import cn.estsh.i3plus.pojo.base.bean.BaseBean;
import cn.estsh.impp.framework.boot.util.ResultBean;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* @Description :
* @Reference :
* @Author : Castle
* @CreateDate : 2021/6/17 13:37
* @Modify:
**/
public class HttpUtils {
private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
// trust-https start
private static void trustAllHosts(HttpsURLConnection connection) {
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
connection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}};
// trust-https end
/**
* post
*
* @param url
* @param timeout
* @param requestObj
* @param returnTargClassOfT
* @return
*/
public static ResultBean postBody(String url, int timeout, Object requestObj, Class returnTargClassOfT) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
try {
// connection
URL realUrl = new URL(url);
connection = (HttpURLConnection) realUrl.openConnection();
// trust-https
boolean useHttps = url.startsWith("https");
if (useHttps) {
HttpsURLConnection https = (HttpsURLConnection) connection;
trustAllHosts(https);
}
// connection setting
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setReadTimeout(timeout * 1000);
connection.setConnectTimeout(3 * 1000);
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");
// do connection
connection.connect();
// write requestBody
if (requestObj != null) {
String requestBody = GsonTool.toJson(requestObj);
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.write(requestBody.getBytes("UTF-8"));
dataOutputStream.flush();
dataOutputStream.close();
}
// valid StatusCode
int statusCode = connection.getResponseCode();
if (statusCode != 200) {
return new ReturnT<String>(ReturnT.FAIL_CODE, "rpc remoting fail, StatusCode(" + statusCode + ") invalid. for url : " + url);
}
// result
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
String resultJson = result.toString();
// parse returnT
try {
ReturnT returnT = GsonTool.fromJson(resultJson, ReturnT.class);
return returnT;
} catch (Exception e) {
logger.error("rpc remoting (url=" + url + ") response content invalid(" + resultJson + ").", e);
return new ReturnT<String>(ReturnT.FAIL_CODE, "rpc remoting (url=" + url + ") response content invalid(" + resultJson + ").");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
return new ReturnT<String>(ReturnT.FAIL_CODE, "rpc remoting error(" + e.getMessage() + "), for url : " + url);
} finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
logger.error(e2.getMessage(), e2);
}
}
}
}
Loading…
Cancel
Save