http工具类:调用http接口时绕过SSL证书验证

2023-12-28 17:10:08


一、场景

对接第三方接口时,由于SSL证书验证导致接口对接失败

解决方法:调用接口时绕过SSL


二、X509TrustManager

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/** 
 * 证书信任管理器(用于https请求) 
 * author:vincente  2013-11-5 
 */
//这个证书管理器的作用就是让它信任我们指定的证书,上面的代码意味着信任所有证书,不管是否权威机构颁发。
public class MyX509TrustManager implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}

}


三、HttpUtil

import com.alibaba.fastjson.JSONObject;
import com.xxx.config.MyX509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.HttpURLConnection;
import java.net.URL;



import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class HttpUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);


	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr)
	{
		logger.info(String.format("(httpsRequest)发起https请求地址 --> %s , 请求方法 --> %s , 请求参数 --> %s", requestUrl, requestMethod, outputStr));
		JSONObject jsonObject = null;
		StringBuilder buffer = new StringBuilder();
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader bufferedReader = null;
		HttpsURLConnection httpUrlConn = null;
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
//			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);
			httpUrlConn.setConnectTimeout(2000);
			httpUrlConn.setReadTimeout(2000);
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.connect();
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			inputStream = httpUrlConn.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			jsonObject = JSONObject.parseObject(buffer.toString());
		} catch (Exception e) {
			logger.error("调用接口发生错误", e);
		} finally {
			try {
				if (null != bufferedReader){
					bufferedReader.close();
				}

				if (null != inputStreamReader){
					inputStreamReader.close();
				}

				if (null != inputStream){
					inputStream.close();
				}

				if (null != httpUrlConn){
					httpUrlConn.disconnect();
				}
			} catch (Exception e1) {
				logger.error("强制关闭接口的连接对象时发生错误!" + e1.getMessage());
			}
		}
		logger.info(String.format("(httpsRequest)请求接口返回信息.  https请求地址 --> %s,  返回结果 --> %s", requestUrl, jsonObject));
		return jsonObject;
	}
}

文章来源:https://blog.csdn.net/weixin_52116015/article/details/135272503
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。