本文主要是介绍Java 高性能网络数据传输工具-okhttp,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
概述
OKHttp是处理网络请求的HTTP开源框架,它支持GET和POST请求,支持http协议的文件上传和下载,是目前使用比较多的用于网络请求通信的工具; 目前项目需求是需要通过代理服务器将项目业务数据对接到其他部门的系统,采用了性能比较高的okhttp工具进行实现网络数据传输~
项目实践
- 首先Maven引入依赖
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>${okhttp.version}</version>
</dependency>
- 创建HttpClientBuilder客户端访问类
package com.bierce.util;import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;public class HttpClientBuilder {// 创建OkHttpClient单例对象private static OkHttpClient okHttpClient;// 创建OkHttpClient单例对象(适用于自定义超时情景)private static OkHttpClient okHttpClient_custom;// 创建HttpClientBuilder单例,使用饿汉模式private static HttpClientBuilder instance = new HttpClientBuilder();// 锁对象private static Object lock = new Object();// 初始化 OKHttpClient @SuppressWarnings("deprecation")private HttpClientBuilder() {Builder clientBuilder = new Builder();// 设置默认超时(读取/连接/提交数据超时)clientBuilder.readTimeout(180, TimeUnit.SECONDS); // 读取超时clientBuilder.connectTimeout(30, TimeUnit.SECONDS); // 连接超时clientBuilder.writeTimeout(180, TimeUnit.SECONDS); // 写入超时// 支持HTTPS请求,跳过证书验证clientBuilder.sslSocketFactory(createSSLSocketFactory());clientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});okHttpClient = clientBuilder.build();}// 返回实例public static HttpClientBuilder getInstance() {return HttpClientBuilder.instance;}// 默认使用 OkHttpClient 对象public OkHttpClient getOkHttpClient() {return HttpClientBuilder.okHttpClient;}// 自定义okHttpClient_custom对象,高并发下保证对象安全public OkHttpClient getOtherOkHttpClient(long readTimeout, long connectTimeout, long writeTimeout) {synchronized (lock) {if(okHttpClient_custom == null) {Builder clientBuilder = new Builder();// 设置默认超时,比如:读取数据超时, 连接超时, 提交数据超时clientBuilder.readTimeout(readTimeout, TimeUnit.SECONDS); // 读取超时clientBuilder.connectTimeout(connectTimeout, TimeUnit.SECONDS); // 连接超时clientBuilder.writeTimeout(writeTimeout, TimeUnit.SECONDS); // 写入超时// 支持HTTPS请求,跳过证书验证clientBuilder.sslSocketFactory(createSSLSocketFactory());clientBuilder.sslSocketFactory(null, null);clientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});okHttpClient_custom = clientBuilder.build();}return okHttpClient_custom;}}private SSLSocketFactory createSSLSocketFactory() {SSLSocketFactory ssfFactory = null;try {SSLContext sc = SSLContext.getInstance("TLS");sc.init(null, new TrustManager[] { new TrustAllCerts() }, new SecureRandom());ssfFactory = sc.getSocketFactory();} catch (Exception e) {e.printStackTrace();}return ssfFactory;}// 用于信任所有证书class TrustAllCerts implements X509TrustManager {@Overridepublic void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}}
}
- 封装请求方法
// 调用代理服务器, 访问外部系统接口(需要指定方法名)
public static String GetHttpRawData(String requestBodyJsonStr, String webServiceMethod) {......String transfer_BASE_URL = http://10.170.225.220/externalSys/getRawData.asmx; //基于SOAP服务String transfer_Url = transfer_BASE_URL + "/" + webServiceMethod;// 设置表单参数FormBody.Builder formBodyBuilder = new FormBody.Builder();formBodyBuilder.add("httpJson", requestBodyJsonStr);// 创建默认的Builderokhttp3.Request.Builder builder = new Request.Builder();Request request = builder.url(transfer_Url).post(formBodyBuilder.build()).build();//请求客户端OkHttpClient okHttpClient = HttpClientBuilder.getInstance().getOkHttpClient(); Call call = okHttpClient.newCall(request);Response response = call.execute();......
}
- 使用接口
//直接返回外部接口返回内容
......
ProxyServeRequestBody ProxyServeRequestBody = new ProxyServeRequestBody();// 自定义请求代理的请求体:其中会将我们项目中的业务数据进行加密以及设置请求方式等
ObjectMapper om = new ObjectMapper(); // 非常流行的 JSON 处理库 Jackson 的核心类
String requestBodyJsonStr = om.writeValueAsString(proxyServeRequestBody); // 将Java对象序列化成 JSON格式的字符串String webServiceMethod = "GetRawData";
String resultStr = GetHttpRawData(requestBodyJsonStr, webServiceMethod); //获取到请求返回的目标值
......
这篇关于Java 高性能网络数据传输工具-okhttp的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!