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

目录

    • 一、场景
    • 二、X509TrustManager
    • 三、HttpUtil


一、场景

对接第三方接口时,由于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;
	}
}

你可能感兴趣的:(HTTP接口,Java工具类,http,ssl,网络协议)