okhttp工具类:
package com.test.testdemo;import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.TimeUnit;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;import static android.content.ContentValues.TAG;/**** @author MyPC* @date 2018/4/11*/public class OkHttpHelper {private OkHttpClient okHttpClient;private RequestBody requestBody;private Request request;private Handler mHandler;private String url;private Context mContext;private String method = "get";private volatile static OkHttpHelper instance;public static final int HTTP_SUCCESS = 1;public static final int HTTP_FAILURE = 0;public static class ReqMethod {public static String POST = "post";public static String GET = "get";}public OkHttpHelper(Context context) {this.mContext = context;OkHttpClient.Builder builder = new OkHttpClient.Builder();builder.connectTimeout(10000, TimeUnit.MICROSECONDS);X509TrustManager trustManager;SSLSocketFactory sslSocketFactory;try {trustManager = trustManagerForCertificates(trustedCertificatesInputStream());SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, new TrustManager[] { trustManager }, null);sslSocketFactory = sslContext.getSocketFactory();} catch (GeneralSecurityException e) {throw new RuntimeException(e);}builder.sslSocketFactory(sslSocketFactory, trustManager);builder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {Certificate[] localCertificates = new Certificate[0];try {//获取证书链中的所有证书localCertificates = session.getPeerCertificates();} catch (SSLPeerUnverifiedException e) {e.printStackTrace();}//打印所有证书内容for (Certificate c : localCertificates) {Log.d(TAG, "verify: "+c.toString());}return true;}});okHttpClient = builder.build();}public static OkHttpHelper newInstance(Context context){if (instance == null){synchronized (OkHttpHelper.class){if (instance == null){instance = new OkHttpHelper(context);}}}return instance;}public OkHttpHelper addRequestBody(RequestBody body){this.requestBody = body;return this;}public OkHttpHelper addUrl(String url){this.url = url;return this;}public OkHttpHelper setMethod(String method) {this.method = method;return this;}public OkHttpHelper addHandler(Handler handler){this.mHandler = handler;return this;}public void start(){if (method.equals(ReqMethod.POST)){if (requestBody==null){return;}request = new Request.Builder().url(url).addHeader("Accept","application/json; charset=utf-8").post(requestBody).tag(url).build();} else {request = new Request.Builder().url(url).tag(url).build();}okHttpClient.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(final Call call, final IOException e) {if (mHandler!=null){Message message = new Message();message.what = 0;Bundle bundle = new Bundle();bundle.putSerializable("IOException",e);message.setData(bundle);mHandler.sendMessage(message);}}@Overridepublic void onResponse(final Call call, Response response) throws IOException {final String rep = response.body().string();if (rep!=null&&mHandler!=null){Message message = new Message();message.what = 1;Bundle bundle = new Bundle();bundle.putString("Response",rep);message.setData(bundle);mHandler.sendMessage(message);}}});}private InputStream trustedCertificatesInputStream() {InputStream inputStream = null;try {inputStream = mContext.getAssets().open("yghq.cer");} catch (IOException e) {e.printStackTrace();}return inputStream;}private X509TrustManager trustManagerForCertificates(InputStream in)throws GeneralSecurityException {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);if (certificates.isEmpty()) {throw new IllegalArgumentException("expected non-empty set of trusted certificates");}char[] password = "password".toCharArray();// Put the certificates a key store.KeyStore keyStore = newEmptyKeyStore(password);int index = 0;for (Certificate certificate : certificates) {Log.d(TAG, "trustManagerForCertificates: "+certificate.toString());String certificateAlias = Integer.toString(index++);keyStore.setCertificateEntry(certificateAlias, certificate);}// Use it to build an X509 trust manager.KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(keyStore, password);TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(keyStore);TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {throw new IllegalStateException("Unexpected default trust managers:"+ Arrays.toString(trustManagers));}return (X509TrustManager) trustManagers[0];}private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {try {KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());InputStream in = null;keyStore.load(in,password);return keyStore;} catch (IOException e) {throw new AssertionError(e);}}}

使用方法:

String url = "https://192.168.10.125/manager/";
OkHttpHelper.newInstance(this).addUrl(url).setMethod(OkHttpHelper.ReqMethod.GET).addHandler(new Handler(){@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);Bundle bundle = msg.getData();switch (msg.what){case 0:IOException e = (IOException) bundle.getSerializable("IOException");tv_body.setText(e.getMessage());break;case 1:String response = bundle.getString("Response");tv_body.setText(response);break;default:}}}).start();

okhttp3发送https请求相关推荐

  1. VS2015编译Poco+openssl,使用Poco发送HTTPS请求

    下载源码.安装Openssl 下载Poco源码 git clone https://github.com/pocoproject/poco.git openssl下载安装: 下载地址:http://s ...

  2. RestTemplate 发送 Https 请求调用

    RestTemplate 发送 Https 请求调用 个人博客:https://jacob.org.cn import org.apache.http.conn.ssl.NoopHostnameVer ...

  3. 【Spring】Feign客户端发送HTTPS请求绕过认证

    1.概述 转载:https://www.jianshu.com/p/ea627708ab52 一个Spring Boot项目,为了使用Harbor仓库,起初通过Spring RestTemplate完 ...

  4. springboot 使用restTemplate 发送https请求 忽略ssl证书

    最近在写接口的时候给对方回推数据,发送https请求的时候遇到这么个报错:javax.net.ssl.SSLHandshakeException: sun.security.validator.Val ...

  5. C程序|实现使用OPENSSL库 发送HTTPS请求,并接收数据|例如请求12306获取高铁、动车、火车车次信息的方法

    C程序|实现使用OPENSSL库 发送HTTPS请求,并接收数据|例如请求12306获取高铁.动车.火车车次信息的方法 1 HTTPS请求 1.1 研究浏览器发送的请求数据 1.2 代码实现 2 分析 ...

  6. HttpClient发送Https请求报 : unable to find valid certification path to requested target

    一.场景   近期在对接第三方接口时,通过HttpClient发送Https请求报 : unable to find valid certification path to requested tar ...

  7. JS(HTTP页面)发送HTTPS请求、同源策略

    今天遇到一个必须在前端HTTP页面发送HTTPS请求的功能,有点小尴尬,这个跨域问题,也没啥好的解决方式,我网上查了一下,也没啥好的方式! 后来总结了一下,有两种方式: 1.a标签 <a hre ...

  8. js发送https请求问题处理总结

    问题1 1.浏览器端无法发送https请求的时候 使用nginx进行转发,具体配置比较简单 问题2: 构建表单传送数据,提示缺失必要的参数. { "error" : "i ...

  9. Python urllib3和requests发送HTTPS请求时出现SSLError或InsecureRequestWarning

    目录 问题及原因分析 优先考虑的解决方法: 下载证书 使用证书 手动获取证书 不推荐使用的备用解决方法: 关闭方法 衍生问题 参考文档 问题及原因分析 在我们通过urllib3和requests进行H ...

最新文章

  1. 使用jQuery检查输入是否为空
  2. go context包的WithTimeout和WithCancel的使用
  3. spring7: di依赖注入--设值注入
  4. 黄金的商品属性,货币属性,金融属性
  5. 四篇关于恶意软件对抗方面的paper要点
  6. vue-router之 beforeRouteEnter
  7. php中改变函数路由,通过PHP重启路由器以更换IP(原创)
  8. mysql------事务
  9. android 自定义view 水波纹进度球
  10. 遭遇Asp.Net长文件名下载的问题和解决办法
  11. 关于PreScan的Vissim插件
  12. 迅捷屏幕录像工具录制视频使用方法
  13. 安卓微信本地数据库解密
  14. element-UI中分页组件显示英文的解决方案
  15. ​smooth-signature​.js: 前端canvas实现H5带笔锋手写签名,支持PC端和移动端使用,无框架限制,Vue、React等均可使用
  16. Kaldi-Timit 训练
  17. 百度api文字转语音效果
  18. Powerdesigner(16.6) 导出漂亮的word(实用型)
  19. T20,寻寻觅觅冷冷清清凄凄惨惨切切。。。
  20. 雪碧新年神兽主题的观后

热门文章

  1. win7使用网卡开启WIFI功能
  2. linux目录和cat命令
  3. 记录Access deined: authorize failure的坑
  4. 海康摄像头字符叠加详解
  5. 谷歌seo关键词怎么做?Google如何优化关键词
  6. 神通数据库v7.0试用版安装步骤
  7. 作为一名合格的大学生,如何在B站愉快的学习
  8. ##MYfirstLog
  9. 正交变换法中的A矩阵怎么求
  10. 嵌入式行业是个坑吗?