Rest(okhhtp)
Wed Dec 21 2022 06:23:40 GMT+0000 (Coordinated Universal Time)
package com.cyberspace.tla.migrate.utils;
import com.cyberspace.tla.migrate.config.ConfigLoad;
import com.google.gson.JsonObject;
import javafx.util.Pair;
import okhttp3.*;
import okhttp3.OkHttpClient.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class RESTUtil {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
public static Logger LOG = LoggerFactory.getLogger(RESTUtil.class);
static OkHttpClient client = null;
static OkHttpClient getClient(){
if(client == null){
client = new OkHttpClient();
client = trustAllSslClient(client);
}
return client;
}
/*
* This is very bad practice and should NOT be used in production.
*/
private static final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
private static final SSLContext trustAllSslContext;
static {
try {
trustAllSslContext = SSLContext.getInstance("SSL");
trustAllSslContext.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException(e);
}
}
private static final SSLSocketFactory trustAllSslSocketFactory = trustAllSslContext.getSocketFactory();
public static OkHttpClient trustAllSslClient(OkHttpClient client) {
// LOG.warn("Using the trustAllSslClient is highly discouraged and should not be used in Production!");
int timeoutInSec = Integer.parseInt(ConfigLoad.getConfigLoad().getConfig("service.timeout.sec"));
// int timeoutInSec = 5;
Builder builder = client.newBuilder()
.writeTimeout(timeoutInSec, TimeUnit.SECONDS)
.readTimeout(timeoutInSec, TimeUnit.SECONDS);
builder.sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return builder.build();
}
public static String post(String url, String json, Map<String, String> headers) throws IOException {
if (headers == null) {
headers = new HashMap<>();
}
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.headers(Headers.of(headers))
.build();
try {
LOG.info("send json " + json + " to url " + url);
Response response = getClient().newCall(request).execute();
String ans = response.body().string();
return ans;
} catch (SocketTimeoutException e){
LOG.error("TIME OUT, " + e.getMessage());
JsonObject timeOutObj = new JsonObject();
String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
timeOutObj.addProperty("error", timeOutError);
return GsonUtil.toJson(timeOutObj);
} catch (IOException e) {
LOG.error(e.getMessage());
JsonObject timeOutObj = new JsonObject();
String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
timeOutObj.addProperty("error", noDataError);
return GsonUtil.toJson(timeOutObj);
}
}
public static String postNoLog(String url, String json, Map<String, String> headers) throws IOException {
if (headers == null) {
headers = new HashMap<>();
}
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.headers(Headers.of(headers))
.build();
try {
Response response = getClient().newCall(request).execute();
String ans = response.body().string();
return ans;
} catch (SocketTimeoutException e){
LOG.error("TIME OUT, " + e.getMessage());
JsonObject timeOutObj = new JsonObject();
String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
timeOutObj.addProperty("error", timeOutError);
System.out.println("timeout");
return GsonUtil.toJson(timeOutObj);
} catch (IOException e) {
LOG.error(e.getMessage());
JsonObject timeOutObj = new JsonObject();
String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
timeOutObj.addProperty("error", noDataError);
System.out.println("no data");
return GsonUtil.toJson(timeOutObj);
}
}
public static String post(String url, List<Pair<String, String>> form, Map<String, String> headers) throws IOException {
if (headers == null) {
headers = new HashMap<>();
}
String stringForm = "";
for (Pair<String, String> param: form) {
stringForm += "&"+ param.getKey() +"="+ param.getValue();
}
stringForm = stringForm.substring(1);
RequestBody body = RequestBody.create(FORM, stringForm);
Request request = new Request.Builder()
.url(url)
.post(body)
.headers(Headers.of(headers))
.build();
try {
LOG.info("send formdata " + stringForm + " to url " + url);
Response response = getClient().newCall(request).execute();
String ans = response.body().string();
return ans;
} catch (SocketTimeoutException e){
LOG.error("TIME OUT, " + e.getMessage());
JsonObject timeOutObj = new JsonObject();
String timeOutError = ConfigLoad.getConfigLoad().getConfig("error.timeout");
timeOutObj.addProperty("error", timeOutError);
return GsonUtil.toJson(timeOutObj);
} catch (IOException e) {
LOG.error(e.getMessage());
JsonObject timeOutObj = new JsonObject();
String noDataError = ConfigLoad.getConfigLoad().getConfig("error.nodata");
timeOutObj.addProperty("error", noDataError);
return GsonUtil.toJson(timeOutObj);
}
}
public static String get(String url, Map<String, String> headers) throws IOException {
String result = "{}";
try{
if (headers == null) {
headers = new HashMap<>();
}
Request request = new Request.Builder()
.url(url)
.get()
.headers(Headers.of(headers))
.build();
LOG.info("Get url " + url);
LOG.info("Header: " + headers);
Response response = getClient().newCall(request).execute();
result = response.body().string();
// LOG.info("Response: " + result);
}catch (SocketTimeoutException e){
LOG.error("Time out when get url " + url);
JsonObject timeOutObj = new JsonObject();
timeOutObj.addProperty("isTimeOut", "true");
return GsonUtil.toJson(timeOutObj);
}catch (Exception e){
LOG.error(e.getMessage());
}
return result;
}
public static String get(String url, Map<String, String> headers, Map<String, String> params){
String result = "{}";
try{
if (headers == null) {
headers = new HashMap<>();
}
// create Http url with adding params
HttpUrl.Builder httpUrl = HttpUrl.parse(url).newBuilder();
if(params != null){
for(Map.Entry<String, String> param : params.entrySet()) {
httpUrl.addQueryParameter(param.getKey(),param.getValue());
}
}
Request request = new Request.Builder()
.url(httpUrl.build())
.get()
.headers(Headers.of(headers))
.build();
LOG.info("Get url " + url);
LOG.info("Header: " + headers);
LOG.info("Params" + params);
Response response = getClient().newCall(request).execute();
result = response.body().string();
// LOG.info("Response: " + result);
}catch (SocketTimeoutException e){
LOG.error("Time out when get url " + url);
JsonObject timeOutObj = new JsonObject();
timeOutObj.addProperty("isTimeOut", "true");
return GsonUtil.toJson(timeOutObj);
}catch (Exception e){
LOG.error(e.getMessage());
}
return result;
}
}



Comments