httpclient支持加密简易封装

本文介绍了一种使用OkHttp进行HTTPS请求的方法,重点在于如何升级到TLS1.2版本以提高安全性,并提供了多种请求方式的实现代码,包括GET、POST等。

基于okhttp-3.12.12.jar  okio-1.15.0.jar

下载地址:https://download.youkuaiyun.com/download/qq_26377811/12838831

基于产品被扫描出安全漏洞后,有okhttp2.7.5升级支持TLS1.2版本

升级后请求抓包验证成功

资源:

package com.bkcc.util;


import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

/**
 * @create 2020-09-11 19:20
 * @description Http请求工具
 */
@Slf4j
public class OkHttpUtil {
	
	private static OkHttpClient singleton;
	
	/**
	 * OkHttpUtil
	 */
	private OkHttpUtil() {
	}
	
	/**
	 * DEFAULT_TRUST_MANAGERS
	 */
	private static final X509TrustManager DEFAULT_TRUST_MANAGERS = new X509TrustManager() {

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

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			// TODO Auto-generated method stub
			
		}
	};

	/**
	 * @return
	 */
	public static OkHttpClient getInstance() {
		if (null == singleton) {
			synchronized (OkHttpUtil.class) {
				if (null == singleton) {
					singleton = new OkHttpClient.Builder()
							.connectTimeout(10, TimeUnit.SECONDS)
							.readTimeout(120, TimeUnit.SECONDS).sslSocketFactory(new TLSSocketFactory(DEFAULT_TRUST_MANAGERS), DEFAULT_TRUST_MANAGERS)
                            .build();
				}
			}
		}
		return singleton;
	}

    /**
     * get请求-通过url获取string
     * @param url 请求的url
     * @return
     */
	public static String getStringFromServerByGet(String url) {
		String result = "";
		try {
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildGetRequest(url))
                    .execute();
			if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
			result = response.body().string();
		} catch (IOException e) {
			log.error("getStringFromServerByGet error: ",e);
		}
		return result;
	}

    /**
     * get请求-通过url获取string-带请求头
     * @param url 请求的url
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
	public static String getStringFromServerByGetWithHeader(String url,String headerKey,String headerValue) {
		String result = "";
		try {
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildGetRequestWithHeader(url,headerKey,headerValue))
                    .execute();
			if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
			result = response.body().string();
		} catch (IOException e) {
			log.error("getStringFromServerByGetWithHeader error: ",e);
		}
		return result;
	}

    /**
     * post请求-通过url和parameterJsonType获取string
     * @param url 请求的url
     * @param parameterJsonType 请求的json字符串
     * @return
     */
	public static String getStringFromServerByPostWithJsonString(String url,String parameterJsonType) {
		String result = "";
		try {
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildPostJsonRequest(url,parameterJsonType))
                    .execute();
			if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
			result = response.body().string();
		} catch (IOException e) {
			log.error("getStringFromServerByPostWithJsonString error: ",e);
		}
		return result;
	}

    /**
     * post请求-通过url和parameterJsonType获取string-带请求头
     * @param url 请求的url
     * @param parameterJsonType 请求的json字符串
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
    public static String getStringFromServerByPostWithJsonStringWithHeader(String url,String parameterJsonType,String headerKey,String headerValue) {
        String result = "";
        try {
            Response response = getInstance()
                    .newCall(OkHttpRequestUtil.buildPostJsonRequestWithHeader(url,parameterJsonType,headerKey,headerValue))
                    .execute();
            if (!response.isSuccessful()) {
                throw new IOException("服务器端错误:" + response);
            }
            result = response.body().string();
        } catch (IOException e) {
            log.error("getStringFromServerByPostWithJsonStringWithHeader error: ",e);
        }
        return result;
    }

    /**
     * post请求-通过url和params获取string
     * @param url 请求的url
     * @param params 请求的Map参数
     * @return
     */
	public static String getStringFromServerByPostFormData(String url, Map<String,Object> params){
		String result = "";
		try {
			FormBody.Builder formBodyBuilder = new FormBody.Builder();
			Set<String> keySet = params.keySet();
			for(String key : keySet) {
			String value = String.valueOf(params.get(key));
				formBodyBuilder.add(key,value);
			}
			FormBody formBody = formBodyBuilder.build();
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildPostFormDataRequest(url,formBody))
                    .execute();
			if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
			result = response.body().string();
		} catch (IOException e){
			log.error("getStringFromServerByPostFormData error: ",e);
		}
		return result;
	}

    /**
     * post请求-通过url和params-获取cookie
     * @param url 请求的url
     * @param params 请求的Map参数
     * @return
     */
	public static String getCookieFromServerByPostFormData(String url, Map<String,Object> params){
		String result = "";
		try {
			FormBody.Builder formBodyBuilder = new FormBody.Builder();
			Set<String> keySet = params.keySet();
			for(String key : keySet) {
				String value = String.valueOf(params.get(key));
				formBodyBuilder.add(key,value);
			}
			FormBody formBody = formBodyBuilder.build();
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildPostFormDataRequest(url,formBody))
                    .execute();
            int code = response.code();
            if (code == 200) {
                Headers headers = response.headers();// 获取头信息
                List<String> cookies = headers.values("Set-Cookie");// 获取cookie
                String cookiesArr[] = cookies.toString().split(";");// 保存cookie数据
                result = cookiesArr[0].substring(9);
            }
            if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
		} catch (IOException e){
			log.error("getCookieFromServerByPostFormData error: ",e);
		}
		return result;
	}

    /**
     * post请求-通过url和params获取string-带请求头
     * @param url 请求的url
     * @param params 请求的Map参数
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
    public static String getStringFromServerByPostFormDataWithHeader(String url, Map<String,Object> params,String headerKey,String headerValue){
        String result = "";
        try {
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            Set<String> keySet = params.keySet();
            for(String key : keySet) {
                String value = String.valueOf(params.get(key));
                formBodyBuilder.add(key,value);
            }
            FormBody formBody = formBodyBuilder.build();
            Response response = getInstance()
                    .newCall(OkHttpRequestUtil.buildPostFormDataRequestWithHeader(url,formBody,headerKey,headerValue))
                    .execute();
            if (!response.isSuccessful()) {
                throw new IOException("服务器端错误:" + response);
            }
            result = response.body().string();
        } catch (IOException e){
            log.error("getStringFromServerByPostFormDataWithHeader error: ",e);
        }
        return result;
    }

    /**
     * post请求-通过url和空参-带请求头
     * @param url 请求的url
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
    public static String getStringFromServerByPostWithHeader(String url, String headerKey,String headerValue){
        String result = "";
        try {
            Response response = getInstance()
                    .newCall(OkHttpRequestUtil.buildPostFormDataRequestWithHeader(url,headerKey,headerValue))
                    .execute();
            if (!response.isSuccessful()) {
                throw new IOException("服务器端错误:" + response);
            }
            result = response.body().string();
        } catch (IOException e){
            log.error("getStringFromServerByPostFormDataWithHeader error: ",e);
        }
        return result;
    }

	/**
	 * post请求-通过url和空参-带请求头
	 * @param url 请求的url
	 * @param headerKey1 请求头1
	 * @param headerValue1 请求体1
	 * @param headerKey2 请求头2
	 * @param headerValue2 请求体2
	 * @return
	 */
	public static String getStringFromServerByPostWithHeader2(String url,  String headerKey1,String headerValue1,String headerKey2,String headerValue2){
		String result = "";
		try {
			Response response = getInstance()
					.newCall(OkHttpRequestUtil.buildPostFormDataRequestWithHeader2(url,headerKey1,headerValue1,headerKey2,headerValue2))
					.execute();
			if (!response.isSuccessful()) {
				throw new IOException("服务器端错误:" + response);
			}
			result = response.body().string();
		} catch (IOException e){
			log.error("getStringFromServerByPostFormDataWithHeader error: ",e);
		}
		return result;
	}
}

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @create 2020-09-11 19:30
 * @description Http Request请求工具
 */
public class OkHttpRequestUtil {
	private static final MediaType TYPE_JSON = MediaType.parse("application/json;charset=utf-8");
	private OkHttpRequestUtil() {
	}

    /**
     * get请求
     * @param url 请求的url
     * @return
     */
	public static Request buildGetRequest(String url) {
		return new Request.Builder()
				.url(url)
				.get().build();
	}

	/**
	 * get请求-带请求头的
     * @param url 请求的url
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
	public static Request buildGetRequestWithHeader(String url,String headerKey,String headerValue) {
		return new Request.Builder()
				.url(url)
				.addHeader(headerKey,headerValue)
				.get().build();
	}

	/**
	 * post请求-json字符串
     * @param url 请求的url
     * @param jsonStr 请求的json字符串
     * @return
     */
	public static Request buildPostJsonRequest(String url, String jsonStr) {
		RequestBody requestBody = RequestBody.create(TYPE_JSON, jsonStr);
		return  new Request.Builder()
				.url(url)
				.post(requestBody).build();
	}

    /**
     * post请求-json字符串-带请求头
     * @param url 请求的url
     * @param jsonStr 请求的json字符串
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
    public static Request buildPostJsonRequestWithHeader(String url, String jsonStr,String headerKey,String headerValue) {
        RequestBody requestBody = RequestBody.create(TYPE_JSON, jsonStr);
        return  new Request.Builder()
                .url(url)
                .addHeader(headerKey, headerValue)
                .post(requestBody).build();
    }

	/**
	 * post请求-表单数据
     * @param url 请求的url
     * @param formBody 请求实体类
     * @return
     */
	public static  Request buildPostFormDataRequest(String url, FormBody formBody){
		 return new Request.Builder()
				 .url(url)
				 .post(formBody).build();
	}
	/**
	 * post请求-表单数据
     * @param url 请求的url
     * @param formBody 请求实体类
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
	public static  Request buildPostFormDataRequestWithHeader(String url, FormBody formBody,String headerKey,String headerValue){
		return new Request.Builder()
				.url(url)
				.addHeader(headerKey, headerValue)
				.post(formBody).build();
	}

    /**
     * post请求-空参
     * @param url 请求的url
     * @param headerKey 请求头
     * @param headerValue 请求体
     * @return
     */
    public static  Request buildPostFormDataRequestWithHeader(String url, String headerKey,String headerValue){
        return new Request.Builder()
                .url(url)
                .addHeader(headerKey, headerValue)
                .post(RequestBody.create(null, "")).build();
    }

	/**
	 * post请求-空参
	 * @param url 请求的url
	 * @param headerKey1 请求头1
	 * @param headerValue1 请求体1
	 * @param headerKey2 请求头2
	 * @param headerValue2 请求体2
	 * @return
	 */
	public static  Request buildPostFormDataRequestWithHeader2(String url, String headerKey1,String headerValue1,String headerKey2,String headerValue2){
		return new Request.Builder()
				.url(url)
				.addHeader(headerKey1, headerValue1)
				.addHeader(headerKey2, headerValue2)
				.post(RequestBody.create(null, "")).build();
	}

}


import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class TLSSocketFactory extends SSLSocketFactory {

	/**
	 * PROTOCOL_ARRAY
	 */
	private static final String PROTOCOL_ARRAY[] = new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" };

	/**
	 * @param socket
	 */
	private static void setSupportProtocolAndCipherSuites(Socket socket) {
		if (socket instanceof SSLSocket) {
			((SSLSocket) socket).setEnabledProtocols(PROTOCOL_ARRAY);
		}
	}

	/**
	 * delegate
	 */
	private SSLSocketFactory delegate;

	/**
	 * @param trustManager
	 */
	public TLSSocketFactory(final X509TrustManager trustManager) {
		try {
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
			delegate = sslContext.getSocketFactory();
		} catch (GeneralSecurityException e) {
			throw new AssertionError();
		}
	}

	/**
	 * @param factory
	 */
	public TLSSocketFactory(SSLSocketFactory factory) {
		this.delegate = factory;
	}

	@Override
	public String[] getDefaultCipherSuites() {
		return delegate.getDefaultCipherSuites();
	}

	@Override
	public String[] getSupportedCipherSuites() {
		return delegate.getSupportedCipherSuites();
	}

	@Override
	public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
		Socket ssl = delegate.createSocket(s, host, port, autoClose);
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

	@Override
	public Socket createSocket(String host, int port) throws IOException {
		Socket ssl = delegate.createSocket(host, port);
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

	@Override
	public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
		Socket ssl = delegate.createSocket(host, port, localHost, localPort);
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

	@Override
	public Socket createSocket(InetAddress host, int port) throws IOException {
		Socket ssl = delegate.createSocket(host, port);
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

	@Override
	public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
			throws IOException {
		Socket ssl = delegate.createSocket(address, port, localAddress, localPort);
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

	@Override
	public Socket createSocket() throws IOException {
		Socket ssl = delegate.createSocket();
		setSupportProtocolAndCipherSuites(ssl);
		return ssl;
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值