方式一:
在终端使用CURL进行验证,需要在curl后面加上-k(-k就是忽略SSL验证)
curl -k --location --request POST 'https://XXXXXXX:8080/v1/hello' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
-d '{"userName": "hello","password": "world"}'
具体的java代码如下:
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Pattern;
public class CURLHttpUtil {
protected static Logger logger = LoggerFactory.getLogger(CURLHttpUtil.class);
public static String doPost(String url,String jsonParam,Map<String,String> headerMap){
List<String> listCMDS = getPostRequestCMDS(url, jsonParam, headerMap);
return replaceSpecialStr(execCurl(listCMDS.toArray(new String[]{})));
}
private static String execCurl(String[] cmds) {
ProcessBuilder process = new ProcessBuilder(cmds);
logger.debug("execCurl cmds: {}", Arrays.toString(cmds));
Process p = null;
BufferedReader br = null;
try {
p = process.start();
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
builder.append(line).append(System.getProperty("line.separator"));
}
logger.debug("execCurl().builder:{}", builder.toString());
return builder.toString();
} catch (IOException e) {
logger.error("execute curl command error! cmds: {}", Arrays.toString(cmds),e);
}finally {
if(p != null){
p.destroy();
logger.debug("the process closed!");
}
if(br != null){
try {
br.close();
logger.debug("the bufferedReader closed!");
} catch (IOException e) {
logger.error("bufferedReader closed error! ",e);
}
}
}
return null;
}
private static List<String> getPostRequestCMDS(String url, String jsonParam, Map<String, String> headerMap) {
List<String> listCMDS = new ArrayList<>();
listCMDS.add("curl");
//是否绕过SSL验证,非prod环境需要跳过
listCMDS.add("-k");
listCMDS.add("--connect-timeout");
listCMDS.add("25");
listCMDS.add("--max-time");
listCMDS.add("25");
listCMDS.add("--location");
listCMDS.add("POST");
listCMDS.add(url);
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
listCMDS.add("--header");
listCMDS.add(entry.getKey() + ":" + entry.getValue());
}
listCMDS.add("--data-raw");
listCMDS.add(jsonParam);
return listCMDS;
}
private static String replaceSpecialStr(String str) {
return StringUtils.isEmpty(str) ? null : str.replaceAll("\\s*|\t|\r|\n", "");
}
private static boolean isInteger(String str) {
return Objects.nonNull(str) && Pattern.compile("^[-+]?[\\d]*$").matcher(str).matches();
}
}
方式二:
使用jdk自带的javax.net.ssl.HttpsURLConnection
package cn.gt.isc.interm.web.utils.im;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;
import javax.net.ssl.*;
import javax.ws.rs.HttpMethod;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class HttpUtil {
private static final Map<String,Boolean> IGNORE_URL_SSL_MAP = new HashMap<>();
private static final int READ_TIME_OUT = 5000;
private static final int CONNECT_TIME_OUT = 2000;
/**
*
* @param serviceAddress 服务地址,例如https://www.baidu.com
* @param uri 接口uri,例如/v1/hello
* @param paramsMap 请求参数
* @param headers 请求头参数
* @return
*/
public static String jsonPost(String serviceAddress,String uri, Map<String,Object> paramsMap, Map<String,String> headers) {
HttpsURLConnection httpsURLConnection;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
OutputStream out = null;
try {
URL reqUrl = new URL(serviceAddress + uri) ;
//忽略ssl验证
ignoreSsl(serviceAddress);
httpsURLConnection = (HttpsURLConnection) reqUrl.openConnection();
httpsURLConnection.setRequestMethod(HttpMethod.POST);
httpsURLConnection.setReadTimeout(READ_TIME_OUT);
httpsURLConnection.setConnectTimeout(CONNECT_TIME_OUT);
//设置是否向HttpURLConnection输出
httpsURLConnection.setDoOutput(true);
//设置是否从HttpUrlConnection读入,默认为true
httpsURLConnection.setDoInput(true);
//设置是否使用缓存
httpsURLConnection.setUseCaches(false);
if (! CollectionUtils.isEmpty(headers)) {
headers.forEach(httpsURLConnection::setRequestProperty);
}
//建立连接
httpsURLConnection.connect();
//写入请求数据
out = httpsURLConnection.getOutputStream();
out.write(JSONObject.toJSONString(paramsMap).getBytes());
out.flush();
if (httpsURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpsURLConnection.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[512];
while ((len = inputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, len);
}
return byteArrayOutputStream.toString();
}
} catch (Exception e){
e.printStackTrace();
} finally {
if(Objects.nonNull(out)){
try {
out.close();
} catch (Exception ignored) {
}
}
if(Objects.nonNull(inputStream)){
try {
inputStream.close();
} catch (Exception ignored) {
}
}
if(Objects.nonNull(byteArrayOutputStream)){
try {
byteArrayOutputStream.close();
} catch (Exception ignored) {
}
}
}
return null;
}
private static void trustAllHttpsCertificates() throws Exception {
TrustManager[] trustAllCerts = new TrustManager[1];
TrustManager tm = new CustomTrustManager();
trustAllCerts[0] = tm;
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
/**
* 忽略HTTPS请求的SSL证书,这里做了dubbo check,防止重复调用
*/
private static void ignoreSsl(String serviceAddress) throws Exception {
if(IGNORE_URL_SSL_MAP.getOrDefault(serviceAddress,false)){
return;
}
synchronized (HttpUtil.class){
if(IGNORE_URL_SSL_MAP.getOrDefault(serviceAddress,false)){
return;
}
HostnameVerifier hv = (urlHostName, session) -> true;
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);
IGNORE_URL_SSL_MAP.put(serviceAddress,true);
}
}
private static class CustomTrustManager implements TrustManager, X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
}
}