SSL证书验证
rootca证书资源
调用
//信任所有证书
HTTPSCerUtils.setTrustAllCertificate(okHttpBuilder);
//信任raw资源目录下的证书
HTTPSCerUtils.setCertificate(context, okHttpBuilder, R.raw.rootca);
//传入证书字符串
HTTPSCerUtils.setCertificate(context,okHttpBuilder,"!@$#@!$@#^@^#!");
工具方法:
import android.content.Context;import java.io.ByteArrayInputStream; import java.io.InputStream; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager;import okhttp3.OkHttpClient;public class HTTPSCerUtils {//信任所有证书public static void setTrustAllCertificate(OkHttpClient.Builder okHttpClientBuilder) {try {SSLContext sc = SSLContext.getInstance("TLS");X509TrustManager trustAllManager = new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}};sc.init(null, new TrustManager[]{trustAllManager}, new SecureRandom());okHttpClientBuilder.sslSocketFactory(sc.getSocketFactory(), trustAllManager);//如果需要兼容安卓5.0以下,可以使用这句//okHttpClientBuilder.sslSocketFactory(new TLSSocketFactory(), trustAllManager);okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});} catch (Exception e) {e.printStackTrace();}}//只信任指定证书(传入字符串)public static void setCertificate(Context context, OkHttpClient.Builder okHttpClientBuilder, String cerStr) {try {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cerStr.getBytes());Certificate ca = certificateFactory.generateCertificate(byteArrayInputStream);KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(null, null);keyStore.setCertificateEntry("ca", ca);byteArrayInputStream.close();TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(keyStore);SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0]);okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});} catch (Exception e) {e.printStackTrace();}}//只信任指定证书(传入raw资源ID)public static void setCertificate(Context context, OkHttpClient.Builder okHttpClientBuilder, int cerResID) {try {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");InputStream inputStream = context.getResources().openRawResource(cerResID);Certificate ca = certificateFactory.generateCertificate(inputStream);KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(null, null);keyStore.setCertificateEntry("ca", ca);inputStream.close();TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(keyStore);SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0]);okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});} catch (Exception e) {e.printStackTrace();}}//批量信任证书public static void setCertificates(Context context, OkHttpClient.Builder okHttpClientBuilder, int... cerResIDs) {try {CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(null, null);for (int i = 0; i < cerResIDs.length; i++) {Certificate ca = certificateFactory.generateCertificate(context.getResources().openRawResource(cerResIDs[i]));keyStore.setCertificateEntry("ca" + i, ca);}TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(keyStore);SSLContext sslContext = SSLContext.getInstance("TLS");sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) tmf.getTrustManagers()[0]);okHttpClientBuilder.hostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});} catch (Exception e) {e.printStackTrace();}} }
1、导入OKhttp依赖
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
2、创建请求工具类
三个工具类
/*** 作者:created by meixi* 邮箱:15913707499@163.com* 日期:2019/4/10 15*/public class OkhttpUtil {public static final String METHOD_GET = "GET";public static final String METHOD_POST = "POST";public static final String METHOD_PUT = "PUT";public static final String METHOD_DELETE = "DELETE";public static final String FILE_TYPE_FILE = "file/*";public static final String FILE_TYPE_IMAGE = "image/*";public static final String FILE_TYPE_AUDIO = "audio/*";public static final String FILE_TYPE_VIDEO = "video/*";/*** get请求* @param url:url* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpGet(String url, CallBackUtil callBack) {okHttpGet(url, null, null, callBack);}/*** get请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpGet(String url, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpGet(url, paramsMap, null, callBack);}/*** get请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpGet(String url, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_GET, url, paramsMap, headerMap, callBack).execute();}/*** post请求* @param url:url* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPost(String url, CallBackUtil callBack) {okHttpPost(url, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPost(String url, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpPost(url, paramsMap, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPost(String url, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_POST, url, paramsMap, headerMap, callBack).execute();}/*** post请求* @param url:url* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPut(String url, CallBackUtil callBack) {okHttpPut(url, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPut(String url, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpPut(url, paramsMap, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPut(String url, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_PUT, url, paramsMap, headerMap, callBack).execute();}/*** post请求* @param url:url* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpDelete(String url, CallBackUtil callBack) {okHttpDelete(url, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpDelete(String url, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpDelete(url, paramsMap, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpDelete(String url, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_DELETE, url, paramsMap, headerMap, callBack).execute();}/*** post请求,可以传递参数* @param url:url* @param jsonStr:json格式的键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPostJson(String url, String jsonStr, CallBackUtil callBack) {okHttpPostJson(url, jsonStr, null, callBack);}/*** post请求,可以传递参数* @param url:url* @param jsonStr:json格式的键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpPostJson(String url, String jsonStr, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_POST, url, jsonStr, headerMap, callBack).execute();}/*** post请求,上传单个文件* @param url:url* @param file:File对象* @param fileKey:上传参数时file对应的键* @param fileType:File类型,是image,video,audio,file* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度*/public static void okHttpUploadFile(String url, File file, String fileKey, String fileType, CallBackUtil callBack) {okHttpUploadFile(url, file, fileKey,fileType, null, callBack);}/*** post请求,上传单个文件* @param url:url* @param file:File对象* @param fileKey:上传参数时file对应的键* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度*/public static void okHttpUploadFile(String url, File file, String fileKey,String fileType, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpUploadFile(url, file,fileKey, fileType, paramsMap, null, callBack);}/*** post请求,上传单个文件* @param url:url* @param file:File对象* @param fileKey:上传参数时file对应的键* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。还可以重写onProgress方法,得到上传进度*/public static void okHttpUploadFile(String url, File file, String fileKey,String fileType, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_POST, url,paramsMap, file, fileKey,fileType, headerMap, callBack).execute();}/*** post请求,上传多个文件,以list集合的形式* @param url:url* @param fileList:集合元素是File对象* @param fileKey:上传参数时fileList对应的键* @param fileType:File类型,是image,video,audio,file* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadListFile(String url, List<File> fileList, String fileKey, String fileType, CallBackUtil callBack) {okHttpUploadListFile(url,null, fileList, fileKey, fileType, callBack);}/*** post请求,上传多个文件,以list集合的形式* @param url:url* @param fileList:集合元素是File对象* @param fileKey:上传参数时fileList对应的键* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadListFile(String url, Map<String, String> paramsMap,List<File> fileList, String fileKey, String fileType, CallBackUtil callBack) {okHttpUploadListFile(url, paramsMap,fileList, fileKey, fileType, null, callBack);}/*** post请求,上传多个文件,以list集合的形式* @param url:url* @param fileList:集合元素是File对象* @param fileKey:上传参数时fileList对应的键* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadListFile(String url, Map<String, String> paramsMap, List<File> fileList, String fileKey, String fileType, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_POST, url, paramsMap,fileList, fileKey, fileType, headerMap, callBack).execute();}/*** post请求,上传多个文件,以map集合的形式* @param url:url* @param fileMap:集合key是File对象对应的键,集合value是File对象* @param fileType:File类型,是image,video,audio,file* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadMapFile(String url, Map<String, File> fileMap, String fileType, CallBackUtil callBack) {okHttpUploadMapFile(url, fileMap, fileType, null, callBack);}/*** post请求,上传多个文件,以map集合的形式* @param url:url* @param fileMap:集合key是File对象对应的键,集合value是File对象* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadMapFile(String url, Map<String, File> fileMap, String fileType, Map<String, String> paramsMap, CallBackUtil callBack) {okHttpUploadMapFile(url, fileMap, fileType, paramsMap, null, callBack);}/*** post请求,上传多个文件,以map集合的形式* @param url:url* @param fileMap:集合key是File对象对应的键,集合value是File对象* @param fileType:File类型,是image,video,audio,file* @param paramsMap:map集合,封装键值对参数* @param headerMap:map集合,封装请求头键值对* @param callBack:回调接口,onFailure方法在请求失败时调用,onResponse方法在请求成功后调用,这两个方法都执行在UI线程。*/public static void okHttpUploadMapFile(String url, Map<String, File> fileMap, String fileType, Map<String, String> paramsMap, Map<String, String> headerMap, CallBackUtil callBack) {new RequestUtil(METHOD_POST, url,paramsMap, fileMap, fileType, headerMap, callBack).execute();}/*** 下载文件,不带参数*/public static void okHttpDownloadFile(String url,CallBackUtil.CallBackFile callBack) {okHttpDownloadFile(url,null,callBack);}/*** 下载文件,带参数*/public static void okHttpDownloadFile(String url,Map<String, String> paramsMap, CallBackUtil.CallBackFile callBack) {okHttpGet(url, paramsMap, null, callBack);}/*** 加载图片*/public static void okHttpGetBitmap(String url, CallBackUtil.CallBackBitmap callBack) {okHttpGetBitmap(url, null, callBack);}/*** 加载图片,带参数*/public static void okHttpGetBitmap(String url,Map<String, String> paramsMap, CallBackUtil.CallBackBitmap callBack) {okHttpGet(url, paramsMap, null, callBack);}}
3、请求结果
设置超时
/*** 设置连接超时时间*/
public final static int CONNECT_TIMEOUT = 60;
/*** 设置读取超时时间*/
public final static int READ_TIMEOUT = 100;
/*** 设置写的超时时间*/
public final static int WRITE_TIMEOUT = 60;
private OkHttpClient mOkHttpClient;//OKhttpClient对象
mOkHttpClient = new OkHttpClient.Builder().connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间.build();
2、okgo使用实例——非常简洁
public APIClient apiClient = APIClient.getApiClient();
/*** 1,校验&添加设备* 设备不存在-添加并返回成功 设备存在-返回成功*/
private void addOrCheck() {apiClient.post(new APIParams.Builder().pathUrl(Urls.ADDORCHECK).param("deviceNo", App.mDevID).callback(new AbsAPICallback<AddOrCheckBean>() {@Overrideprotected void onSuccess(String subCode, String msg, AddOrCheckBean data) {LogPlus.e("校验或添加成功 cabinetNum = " + data.cabinetNum);App.mGridNum = data.cabinetNum;queryDevInfo();}}).build());}
返回结果
APIParams APIClient
public Map getParamsMap(){return paramMap; }
.params(params.getParamsMap(), false)
private static Gson mGSon; public static String parseObjToJsonStr(Object srcObj) {String result = "";if (mGSon == null) {mGSon = new GsonBuilder().disableHtmlEscaping().create();}try {result = mGSon.toJson(srcObj);} catch (Exception e) {Log.getStackTraceString(e);}return result; }
APIResponseCallback
params.callback.onSuccess(response.body().code, responseInfo, null);
demo云盘链接: 百度网盘 请输入提取码
密码在线回复:QQ1085220040