博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用OkHttp实现HttpClient请求
阅读量:6567 次
发布时间:2019-06-24

本文共 16253 字,大约阅读时间需要 54 分钟。

hot3.png

package com.bjdata.common.utils;import javax.net.ssl.KeyManager;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.security.KeyStore;import java.security.SecureRandom;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;import java.util.Set;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * JFinal-weixin Http请求工具类 *  * @author L.cm */public final class HttpUtils {   private HttpUtils() {   }   public static String get(String url) {      return delegate.get(url);   }   public static String get(String url, Map
queryParas) { return delegate.get(url, queryParas); } public static String post(String url, String data) { return delegate.post(url, data); } public static String post(String url, Map
queryParas) { return delegate.post(url, queryParas); } public static String postSSL(String url, String data, String certPath, String certPass) { return delegate.postSSL(url, data, certPath, certPass); } public static String postSSL(String url, String data, InputStream certFile, String certPass) { return delegate.postSSL(url, data, certPass, certFile); } public static InputStream download(String url, String params) { return delegate.download(url, params); } public static String upload(String url, File file, String params) { return delegate.upload(url, file, params); } /** * http请求工具 委托 优先使用OkHttp 最后使用JFinal HttpKit */ private interface HttpDelegate { String get(String url); String get(String url, Map
queryParas); String post(String url, String data); String post(String url, Map
queryParas); String postSSL(String url, String data, String certPath, String certPass); String postSSL(String url, String data, String certPass, InputStream certFile); InputStream download(String url, String params); String upload(String url, File file, String params); } // http请求工具代理对象 private static final HttpDelegate delegate; static { HttpDelegate delegateToUse = null; // okhttp3.OkHttpClient? if (ClassUtils.isPresent("okhttp3.OkHttpClient", HttpUtils.class.getClassLoader())) { delegateToUse = new OkHttp3Delegate(); } // com.squareup.okhttp.OkHttpClient? else if (ClassUtils.isPresent("com.squareup.okhttp.OkHttpClient", HttpUtils.class.getClassLoader())) { delegateToUse = new OkHttpDelegate(); } // HttpKit? else if (ClassUtils.isPresent("HttpKit", HttpUtils.class.getClassLoader())) { delegateToUse = new HttpKitDelegate(); } delegate = delegateToUse; } /** * OkHttp2代理 */ private static class OkHttpDelegate implements HttpDelegate { private final com.squareup.okhttp.OkHttpClient httpClient; private final com.squareup.okhttp.OkHttpClient httpsClient; Lock lock = new ReentrantLock(); public OkHttpDelegate() { httpClient = new com.squareup.okhttp.OkHttpClient(); // 分别设置Http的连接,写入,读取的超时时间 httpClient.setConnectTimeout(10, TimeUnit.SECONDS); httpClient.setWriteTimeout(10, TimeUnit.SECONDS); httpClient.setReadTimeout(30, TimeUnit.SECONDS); httpsClient = httpClient.clone(); } private static final com.squareup.okhttp.MediaType CONTENT_TYPE_FORM = com.squareup.okhttp.MediaType .parse("application/x-www-form-urlencoded"); private String exec(com.squareup.okhttp.Request request) { try { com.squareup.okhttp.Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String get(String url) { com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url).get().build(); return exec(request); } @Override public String get(String url, Map
queryParas) { com.squareup.okhttp.HttpUrl.Builder urlBuilder = com.squareup.okhttp.HttpUrl.parse(url).newBuilder(); for (Entry
entry : queryParas.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } com.squareup.okhttp.HttpUrl httpUrl = urlBuilder.build(); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(httpUrl).get().build(); return exec(request); } @Override public String post(String url, String params) { com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(CONTENT_TYPE_FORM, params); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url).post(body).build(); return exec(request); } @Override public String post(String url, Map
queryParas) { com.squareup.okhttp.FormEncodingBuilder builder = new com.squareup.okhttp.FormEncodingBuilder(); for (Entry
entry : queryParas.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url) .post(builder.build()).build(); return exec(request); } @Override public String postSSL(String url, String data, String certPass, InputStream certFile) { com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(CONTENT_TYPE_FORM, data); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url).post(body).build(); InputStream inputStream = certFile; try { // 移动到最开始,certPath io异常unlock会报错 lock.lock(); KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(certFile, certPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, certPass.toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); httpsClient.setSslSocketFactory(sslContext.getSocketFactory()); com.squareup.okhttp.Response response = httpsClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(inputStream); lock.unlock(); } } @Override public String postSSL(String url, String data, String certPath, String certPass) { com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(CONTENT_TYPE_FORM, data); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url).post(body).build(); InputStream inputStream = null; try { // 移动到最开始,certPath io异常unlock会报错 lock.lock(); KeyStore clientStore = KeyStore.getInstance("PKCS12"); inputStream = new FileInputStream(certPath); clientStore.load(inputStream, certPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, certPass.toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); httpsClient.setSslSocketFactory(sslContext.getSocketFactory()); com.squareup.okhttp.Response response = httpsClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(inputStream); lock.unlock(); } } @Override public InputStream download(String url, String params) { com.squareup.okhttp.Request request; if (StrKit.notBlank(params)) { com.squareup.okhttp.RequestBody body = com.squareup.okhttp.RequestBody.create(CONTENT_TYPE_FORM, params); request = new com.squareup.okhttp.Request.Builder().url(url).post(body).build(); } else { request = new com.squareup.okhttp.Request.Builder().url(url).get().build(); } try { com.squareup.okhttp.Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().byteStream(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String upload(String url, File file, String params) { com.squareup.okhttp.RequestBody fileBody = com.squareup.okhttp.RequestBody .create(com.squareup.okhttp.MediaType.parse("application/octet-stream"), file); com.squareup.okhttp.MultipartBuilder builder = new com.squareup.okhttp.MultipartBuilder() .type(com.squareup.okhttp.MultipartBuilder.FORM).addFormDataPart("media", file.getName(), fileBody); if (StrKit.notBlank(params)) { builder.addFormDataPart("description", params); } com.squareup.okhttp.RequestBody requestBody = builder.build(); com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder().url(url).post(requestBody) .build(); return exec(request); } } /** * OkHttp3代理 */ private static class OkHttp3Delegate implements HttpDelegate { private okhttp3.OkHttpClient httpClient; public OkHttp3Delegate() { // 分别设置Http的连接,写入,读取的超时时间 httpClient = new okhttp3.OkHttpClient().newBuilder().connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build(); } private static final okhttp3.MediaType CONTENT_TYPE_FORM = okhttp3.MediaType .parse("application/x-www-form-urlencoded"); private String exec(okhttp3.Request request) { try { okhttp3.Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String get(String url) { okhttp3.Request request = new okhttp3.Request.Builder().url(url).get().build(); return exec(request); } @Override public String get(String url, Map
queryParas) { okhttp3.HttpUrl.Builder urlBuilder = okhttp3.HttpUrl.parse(url).newBuilder(); for (Entry
entry : queryParas.entrySet()) { urlBuilder.addQueryParameter(entry.getKey(), entry.getValue()); } okhttp3.HttpUrl httpUrl = urlBuilder.build(); okhttp3.Request request = new okhttp3.Request.Builder().url(httpUrl).get().build(); return exec(request); } @Override public String post(String url, String params) { okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, params); okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(body).build(); return exec(request); } @Override public String postSSL(String url, String data, String certPass, InputStream certFile) { okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, data); okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(body).build(); InputStream inputStream = certFile; try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); char[] passArray = certPass.toCharArray(); clientStore.load(inputStream, passArray); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, passArray); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); @SuppressWarnings("deprecation") okhttp3.OkHttpClient httpsClient = new okhttp3.OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS).sslSocketFactory(sslContext.getSocketFactory()).build(); okhttp3.Response response = httpsClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(inputStream); } } @Override public String postSSL(String url, String data, String certPath, String certPass) { okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, data); okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(body).build(); InputStream inputStream = null; try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); inputStream = new FileInputStream(certPath); char[] passArray = certPass.toCharArray(); clientStore.load(inputStream, passArray); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, passArray); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); @SuppressWarnings("deprecation") okhttp3.OkHttpClient httpsClient = new okhttp3.OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS).sslSocketFactory(sslContext.getSocketFactory()).build(); okhttp3.Response response = httpsClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().string(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(inputStream); } } @Override public InputStream download(String url, String params) { okhttp3.Request request; if (StrKit.notBlank(params)) { okhttp3.RequestBody body = okhttp3.RequestBody.create(CONTENT_TYPE_FORM, params); request = new okhttp3.Request.Builder().url(url).post(body).build(); } else { request = new okhttp3.Request.Builder().url(url).get().build(); } try { okhttp3.Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response); return response.body().byteStream(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String upload(String url, File file, String params) { okhttp3.RequestBody fileBody = okhttp3.RequestBody .create(okhttp3.MediaType.parse("application/octet-stream"), file); okhttp3.MultipartBody.Builder builder = new okhttp3.MultipartBody.Builder() .setType(okhttp3.MultipartBody.FORM).addFormDataPart("media", file.getName(), fileBody); if (StrKit.notBlank(params)) { builder.addFormDataPart("description", params); } okhttp3.RequestBody requestBody = builder.build(); okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(requestBody).build(); return exec(request); } @Override public String post(String url, Map
params) { okhttp3.FormBody.Builder builder = new okhttp3.FormBody.Builder(); if (params == null) { params = new HashMap
(); } if (params != null) { Set
> entries = params.entrySet(); for (Entry
entry : entries) { builder.add(entry.getKey(), entry.getValue()); } } okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(builder.build()).build(); return exec(request); } } /** * HttpKit代理 */ private static class HttpKitDelegate implements HttpDelegate { @Override public String get(String url) { return HttpKit.get(url); } @Override public String get(String url, Map
queryParas) { return HttpKit.get(url, queryParas); } @Override public String post(String url, String data) { return HttpKit.post(url, data); } @Override public String post(String url, Map
queryParas) { return HttpKit.post(url, queryParas, "null"); } @Override public String postSSL(String url, String data, String certPass, InputStream certFile) { return HttpKitExt.postSSL(url, data, certFile, certPass); } @Override public String postSSL(String url, String data, String certPath, String certPass) { return HttpKitExt.postSSL(url, data, certPath, certPass); } @Override public InputStream download(String url, String params) { try { return HttpKitExt.downloadMaterial(url, params); } catch (IOException e) { throw new RuntimeException(e); } } @Override public String upload(String url, File file, String params) { try { return HttpKitExt.uploadMedia(url, file, params); } catch (IOException e) { throw new RuntimeException(e); } } }}

转载于:https://my.oschina.net/u/3193075/blog/3030864

你可能感兴趣的文章
【BZOJ】1105: [POI2007]石头花园SKA
查看>>
MapReduce原理与设计思想
查看>>
Theano学习笔记(三)——图结构
查看>>
UVa - 11400 - Lighting System Design
查看>>
Oracle 11g 客户端使用
查看>>
luvit 被忽视的lua 高性能框架(仿nodejs)
查看>>
也许每个农村出来的码农都有个田园梦
查看>>
J2EE的13种核心技术
查看>>
Express.js 中的 Sessions 如何工作?(译)
查看>>
Web自动化之Headless Chrome概览
查看>>
【133天】尚学堂高淇Java300集视频精华笔记(71-72)
查看>>
剖析 Laravel 计划任务--事件属性
查看>>
百度成立国内首个深度学习教育联盟,将制定行业标准
查看>>
Micronaut教程:如何使用基于JVM的框架构建微服务
查看>>
检查IP是否可用的方法
查看>>
互联网架构师必备技术 Docker仓库与Java应用服务动态发布那些事
查看>>
Intellij IDEA 2018.2 搭建Spring Boot 应用
查看>>
作为数据科学家,我都有哪些弱点
查看>>
(转)线程安全的CopyOnWriteArrayList介绍
查看>>
中交兴路完成7亿元A轮融资,携手蚂蚁金服共建小微物流科技服务生态
查看>>