本文主要是介绍Okhttp3系列之(3) - SpringBoot下配置Okhttp3工具类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.添加pom.xml依赖
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.6.0</version>
</dependency>
2.封装工具类:
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;/*** Created by yunshidi on 2020/7/8.*/
@Slf4j
public class OkHttpUtil {public final static int READ_TIMEOUT = 100;public final static int CONNECT_TIMEOUT = 60;public final static int WRITE_TIMEOUT = 60;public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");public static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");private static final byte[] LOCKER = new byte[0];private static OkHttpUtil mInstance = new OkHttpUtil();private OkHttpClient mOkHttpClient;private static final String KEY_STORE_TYPE_P12 = "PKCS12";//证书类型private static final String KEY_STORE_PASSWORD = "csrysd200628";//ca.p12证书密码(客户端证书密码)/*** 自定义网络回调接口*/public interface NetCall {void success(Call call, Response response) throws IOException;void failed(Call call, IOException e);}private OkHttpUtil() {}private OkHttpClient getOkHttpClient() throws Exception {if (mOkHttpClient != null) {return mOkHttpClient;}// 启用https, 客户端证书(双向认证,需银行提供客户端证书)// KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);// keyStore.load(new FileInputStream("ca.p12"), KEY_STORE_PASSWORD.toCharArray());// KeyManagerFactory证书管理类// KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());// keyManagerFactory.init(keyStore, KEY_STORE_PASSWORD.toCharArray());TrustManager[] trustManagers = new TrustManager[]{new TrustAllCerts()};SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, trustManagers, new SecureRandom());OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();//读取超时clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);//连接超时clientBuilder.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//写入超时clientBuilder.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS);//支持HTTPS请求,跳过证书验证clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]);clientBuilder.hostnameVerifier((hostname, session) -> true);return mOkHttpClient = clientBuilder.build();}/*** 单例模式获取OkHttpUtil** @return*/public static OkHttpUtil getInstance() {return mInstance;}/*** get请求,同步方式,获取网络数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行** @param url* @return*/public Response getData(String url) throws Exception {//1 构造RequestRequest.Builder builder = new Request.Builder();Request request = builder.get().url(url).build();//2 将Request封装为CallCall call = getOkHttpClient().newCall(request);//3 执行Call,得到responseResponse response = null;try {response = call.execute();} catch (IOException e) {e.printStackTrace();}return response;}/*** post请求,同步方式,提交数据,是在主线程中执行的,需要新起线程,将其放到子线程中执行** @param url* @param bodyParams* @return*/public Response postData(String url, Map<String, String> bodyParams) throws Exception {//1构造RequestBodyRequestBody body = setRequestBody(bodyParams);//2 构造RequestRequest.Builder requestBuilder = new Request.Builder();Request request = requestBuilder.post(body).url(url).build();//3 将Request封装为CallCall call = getOkHttpClient().newCall(request);//4 执行Call,得到responseResponse response = null;try {response = call.execute();} catch (IOException e) {e.printStackTrace();}return response;}/*** get请求,异步方式,获取网络数据,是在子线程中执行的,需要切换到主线程才能更新UI** @param url* @param netCall* @return*/public void getDataAsyn(String url, final NetCall netCall) throws Exception {//1 构造RequestRequest.Builder builder = new Request.Builder();Request request = builder.get().url(url).build();//2 将Request封装为CallCall call = getOkHttpClient().newCall(request);//3 执行Callcall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {netCall.failed(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {netCall.success(call, response);}});}/*** post请求,异步方式,提交数据,是在子线程中执行的,需要切换到主线程才能更新UI** @param url* @param bodyParams* @param netCall*/public void postDataAsyn(String url, Map<String, String> bodyParams, final NetCall netCall) throws Exception {//1构造RequestBodyRequestBody body = setRequestBody(bodyParams);//2 构造RequestRequest.Builder requestBuilder = new Request.Builder();Request request = requestBuilder.post(body).url(url).build();//3 将Request封装为CallCall call = getOkHttpClient().newCall(request);//4 执行Callcall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {netCall.failed(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {netCall.success(call, response);}});}/*** post的请求参数,构造RequestBody** @param bodyParams* @return*/private RequestBody setRequestBody(Map<String, String> bodyParams) {RequestBody body = null;FormBody.Builder formEncodingBuilder = new FormBody.Builder();if (bodyParams != null) {Iterator<String> iterator = bodyParams.keySet().iterator();String key = "";while (iterator.hasNext()) {key = iterator.next().toString();formEncodingBuilder.add(key, bodyParams.get(key));// log.info("post_Params=== {} ==== {}" + key, bodyParams.get(key));}}body = formEncodingBuilder.build();return body;}public String postXml(String url, String xml) throws Exception {RequestBody body = RequestBody.create(xml, XML);Request request = new Request.Builder().url(url).post(body).build();Response response = getOkHttpClient().newCall(request).execute();if (response.isSuccessful()) {return response.body().string();} else {throw new IOException("Unexpected code " + response);}}public String postJson(String url, String json) throws Exception {RequestBody body = RequestBody.create(json, JSON);Request request = new Request.Builder().url(url).post(body).build();Response response = getOkHttpClient().newCall(request).execute();if (response.isSuccessful()) {return response.body().string();} else {throw new IOException("Unexpected code " + response);}}public void postJsonAsyn(String url, String json, final NetCall netCall) throws Exception {RequestBody body = RequestBody.create(json,JSON);//2 构造RequestRequest.Builder requestBuilder = new Request.Builder();Request request = requestBuilder.post(body).url(url).build();//3 将Request封装为CallCall call = getOkHttpClient().newCall(request);//4 执行Callcall.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {netCall.failed(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {netCall.success(call, response);}});}/*** 用于信任所有证书*/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 void main(String[] args) throws Exception {Response response = OkHttpUtil.getInstance().getData("http://www.baidu.com");System.out.println(response.body().string());}
}
这篇关于Okhttp3系列之(3) - SpringBoot下配置Okhttp3工具类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!