Android okhttputils 第三方库网络请求库

1.build.gradle中添加依赖库:

//okhttputils..第三方库
implementation 'com.zhy:okhttputils:2.6.2'
implementation 'com.squareup.okhttp3:okhttp:3.7.0'
implementation 'com.squareup.okio:okio:1.14.1'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

2.编写封装工具类

package com.example.documenttransfer.util;


import android.util.Log;

import com.example.documenttransfer.base.BaseApplication;
import com.example.documenttransfer.callback.MyOkHttpUtilsCallBack;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.security.PrivateKey;
import java.security.PublicKey;

import okhttp3.Call;
import okhttp3.MediaType;


public class MyOkHttpUtils {

    //字符串公钥,可以直接保存在客户端
    public static final String PUBLIC_KEY_STR = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDArPDJm7Ey+VGOHdj5X6AH8KGlhmZ7/MTVY3cGY87wJTcS+kAun/Cn1Kk9JnCR946c7b5kReWb9un0I/zFrRgFC369n35I+DbV7lcECs05DseSQo4QmsEzNZrDpQLhFmyHO8JbpYypP1T9XrRGMs3eBCHVBi9ZB//oNG6p9gxpjwIDAQAB";
    //字符串密钥,通常保存在服务器,这里为了方便演示,直接保存在客户端
    public static final String PRIVATE_KEY_STR = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMCs8MmbsTL5UY4d2PlfoAfwoaWGZnv8xNVjdwZjzvAlNxL6QC6f8KfUqT0mcJH3jpztvmRF5Zv26fQj/MWtGAULfr2ffkj4NtXuVwQKzTkOx5JCjhCawTM1msOlAuEWbIc7wluljKk/VP1etEYyzd4EIdUGL1kH/+g0bqn2DGmPAgMBAAECgYAmIxUWEsckO800wBuuYIsghzS3ur6WVBXx1to8XY0cY4FfNEF3+Rh9X86P2Af4HHQSA8zntB4anOj59hWWWwihvo7U6Vn2JsigXzXNM3BcR866yz2PCk7vS8FXKCWdnlGC5y+a2Spe64lzbKhXzy+O30KvNE2rPx7+nM6si7u04QJBAPe1tbDpOUp4DuOlmn3anGOdnQf+7DTT7G4T1+1AcGgtutyq+p3/CC3c5Y/Niek8YVLGTAkK4NODV0LXzn4FqXMCQQDHH7d9P2wF3ZSaUc8Kvv3CtROU29N88CpjGo8DhqX3SAKWxd+iA2ekSe8c5duitAWYxtgG6efPPgMYAd9KFCh1AkA2NVfLnV5iQ5/OhcEnZZ3v1uA0jb8XWIFXHZSVYRK4WbmY7PnndZZOoxbBv5M8rXAG80pUeEL3Rrjj8eJIheitAkEAjKRRRIyULrxnpmvb8boen/SnpP9zLA6x0ZfDpXjoJnVdJsMSBmujO33g/qc3b375aQQhNxjk2xLwuncwEDGWtQJAIXDO38OeaxWg3qhr5/E5yxIx7O4Sj5a36c83INTS7Jjxcz/u7YOVgsYKmYEE5cbOmbGLBqge4usH+Qht72cMnA==";

    /**
     * 设置连接超时时间
     */
    public final static int CONNECT_TIMEOUT = 60;
    /**
     * 设置读取超时时间
     */
    public final static int READ_TIMEOUT = 100;
    /**
     * 设置写的超时时间
     */
    public final static int WRITE_TIMEOUT = 60;

    public static void postStringCallBack(String jsonHead, final String url, final MyOkHttpUtilsCallBack myOkHttpUtilsCallBack) {
        try {
            //加密
            PublicKey publicKey = RSAEncrypt.getPublicKey(PUBLIC_KEY_STR);
            String encrypt = RSAEncrypt.encrypt(jsonHead, publicKey);
            OkHttpUtils
                    .postString()
                    .url(url)
                    .mediaType(MediaType.parse("application/json; charset=utf-8"))
//                    .content(encrypt)
                    .content(jsonHead)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            //接口调用失败
                            LogUtils.e("接口调用失败" + e.toString());
//                            BaseApplication.getApp().writeLogFile(url + "=====接口调用失败====" + e.getMessage());
                            myOkHttpUtilsCallBack.errorCallback(call, e, id);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            PrivateKey privateKey = null;
                            try {
                                //解密成功
//                                privateKey = RSAEncrypt.getPrivateKey(PRIVATE_KEY_STR);
//                                String decrypt = RSAEncrypt.decrypt(response, privateKey);
//                                BaseApplication.getApp().writeLogFile(url + "=====解密成功====" + decrypt);
                                LogUtils.e("接口调用成功");
                                myOkHttpUtilsCallBack.successCallback(response, id);
                            } catch (Exception e) {
                                LogUtils.e(e.toString());
                                BaseApplication.getApp().writeLogFile(url + "=====解密异常====" + e.getMessage());
                            }
                        }
                    });
        } catch (Exception e) {

        }
    }

    /**
     * 请求头加了token
     *
     * @param jsonHead
     * @param url
     * @param myOkHttpUtilsCallBack
     */
    public static void postStringCallBacks(String jsonHead, final String url, final MyOkHttpUtilsCallBack myOkHttpUtilsCallBack) {
        try {
//            String  token = PrefUtils.getString(BaseApplication.getContext(), "token", "");
//            String  expire = PrefUtils.getString(BaseApplication.getContext(), "expire", "");
//            String CRBIMUID = "c5356162f93c11ed81570050568ccd1f";//userId
//            String appKey = "4b7f9fb5252544bcbc820229b436d9a4";//appKey
            String CRBIMUID = "c5356162f93c11ed81570050568ccd1f";//userId
            String Cookie = "language=zh-CN; CRBIMSESSIONID=2B3B6EB2082512DBA24D3F666752866F; CRBIMSSOJWT=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxYmU2YWI1NjVlNDkxMWVjYTcwODAwNTA1NmE2N2E4NiIsImlhdCI6MTY4Nzk1MzI5OSwiaXNzIjoiaHR0cDovL3I5MzUzNSIsImV4cCI6MTY4Nzk1Njg5OSwidVR5cGUiOiIyIiwicHRDb2RlIjoiUFQwMDEiLCJwdFR5cGUiOiIxIiwidmVyc2lvbiI6InYyLjAifQ.OabzCMb4W7xFuGcBk8Q956nJugPyBa4rbZET_aPf4AFoBY6-96fO3lZtUmJir_WX0THU8AA9wuiSMtCn0YGnH2Z-z9ilS3ZlBMxtSdgPEIePbTRdoiwO_Hmr4y7ICcmT8Ot9dqwTzuJjIxfwn9KsiExagAifHUq_k-2hdCqfIFGKO0ai13fvhX-eIFcQn0C52l2v4lYpkc8Zbhii6oXAguAcfNk_y9-HgoMGyR0aRNZ9r2RHKutypNsd1lzcDijsOGP5XXU0qZAwODc0SAKsX8z5IZt2RKY8Lwxq-2OZrCytGQ4LJN4grzSmhY4-ts28RsqppPVvwFV6TKZNZGVtIg; token=48f091cb89bc8310a5defd17c859dd4b; acw_tc=784e2cb216879537138233358e5cee71f560ea8596fa456bff681dd71834af; BIGipServerpool_srxtjk=!Hce4+3FmP3shFMGb/CULM79eIdI1FLfL5ya1HJilBs1ltd45rrHrEIt+89EV9fhm9MoZUNW7r5F5u6s=";//userId
            //加密
//            PublicKey publicKey = RSAEncrypt.getPublicKey(PUBLIC_KEY_STR);
//            String encrypt = RSAEncrypt.encrypt(jsonHead, publicKey);
            String JWT = PrefUtils.getString("JWT", "");
            String cookie = "CRBIMSSOJWT="+ JWT ;
            OkHttpUtils
                    .postString()
                    .url(url)
                    .mediaType(MediaType.parse("application/json; charset=utf-8"))
//                    .content(encrypt)
                    .content(jsonHead)
                    .addHeader("appKey","4b7f9fb5252544bcbc820229b436d9a4")
                    .addHeader("CRBIMUID",CRBIMUID)
                    .addHeader("Cookie",cookie)
                    .build()
                    .connTimeOut(10000)
                    .readTimeOut(10000)
                    .writeTimeOut(10000)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            //接口调用失败
                            LogUtils.e("接口调用失败" + e.toString());
//                            ToastUtils.ShowToast("接口调用失败" + e.getMessage());
//                            BaseApplication.getApp().writeLogFile(url + "=====接口调用失败====" + e.getMessage());
                            myOkHttpUtilsCallBack.errorCallback(call, e, id);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            PrivateKey privateKey = null;
                            try {
                                //解密成功
//                                privateKey = RSAEncrypt.getPrivateKey(PRIVATE_KEY_STR);
//                                String decrypt = RSAEncrypt.decrypt(response, privateKey);
//                                BaseApplication.getApp().writeLogFile(url + "=====解密成功====" + decrypt);
                                LogUtils.e("接口调用成功");
                                myOkHttpUtilsCallBack.successCallback(response, id);
                            } catch (Exception e) {
                                LogUtils.e(e.toString());
                                BaseApplication.getApp().writeLogFile(url + "=====解密异常====" + e.getMessage());
//                                ToastUtils.ShowToast("接口调用失败" + e.getMessage());
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * get请求
     *
     * @param url 请求地址
     */
    public static void getCallBack(final String url, final MyOkHttpUtilsCallBack myOkHttpUtilsCallBack) {
        String CRBIMUID = "c5356162f93c11ed81570050568ccd1f";//userId
        String Cookie = "language=zh-CN; CRBIMSESSIONID=2B3B6EB2082512DBA24D3F666752866F; CRBIMSSOJWT=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxYmU2YWI1NjVlNDkxMWVjYTcwODAwNTA1NmE2N2E4NiIsImlhdCI6MTY4Nzk1MzI5OSwiaXNzIjoiaHR0cDovL3I5MzUzNSIsImV4cCI6MTY4Nzk1Njg5OSwidVR5cGUiOiIyIiwicHRDb2RlIjoiUFQwMDEiLCJwdFR5cGUiOiIxIiwidmVyc2lvbiI6InYyLjAifQ.OabzCMb4W7xFuGcBk8Q956nJugPyBa4rbZET_aPf4AFoBY6-96fO3lZtUmJir_WX0THU8AA9wuiSMtCn0YGnH2Z-z9ilS3ZlBMxtSdgPEIePbTRdoiwO_Hmr4y7ICcmT8Ot9dqwTzuJjIxfwn9KsiExagAifHUq_k-2hdCqfIFGKO0ai13fvhX-eIFcQn0C52l2v4lYpkc8Zbhii6oXAguAcfNk_y9-HgoMGyR0aRNZ9r2RHKutypNsd1lzcDijsOGP5XXU0qZAwODc0SAKsX8z5IZt2RKY8Lwxq-2OZrCytGQ4LJN4grzSmhY4-ts28RsqppPVvwFV6TKZNZGVtIg; token=48f091cb89bc8310a5defd17c859dd4b; acw_tc=784e2cb216879537138233358e5cee71f560ea8596fa456bff681dd71834af; BIGipServerpool_srxtjk=!Hce4+3FmP3shFMGb/CULM79eIdI1FLfL5ya1HJilBs1ltd45rrHrEIt+89EV9fhm9MoZUNW7r5F5u6s=";//userId

        String cookie = "";
        String JWT = PrefUtils.getString("JWT", "");
        if(!JWT.equals("")){
            cookie = "CRBIMSSOJWT="+JWT ;
            FileUtils.stringToTxt(cookie,"wsCookie");
            Log.e("wswswsws","CRBIMSSOJWT="+cookie);
        }

//        ToastUtils.ShowToast("获取到 JWT"+JWT);
        OkHttpUtils
                .get()
                .url(url)
                .addHeader("appKey","4b7f9fb5252544bcbc820229b436d9a4")
//                .addHeader("Cookie",cookie)
                .addHeader("CRBIMUID",CRBIMUID)
                .addHeader("Cookie",Cookie)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //接口调用失败
                        LogUtils.e("接口调用失败" + e.toString());
                        myOkHttpUtilsCallBack.errorCallback(call, e, id);
                        ToastUtils.ShowToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            //解密成功
                            LogUtils.e("接口调用成功");
                            myOkHttpUtilsCallBack.successCallback(response, id);
                        } catch (Exception e) {
                            LogUtils.e(e.toString());
                        }
                    }
                });
    }

}

3.Activity 中使用:

private void getyiBanList(int type, String docName, int currPage, int pageSize) {
  
    String jsonHead = "";
    Map<String, Object> mapHead = new HashMap<>();
    mapHead.put("docName", docName);
    mapHead.put("currPage", currPage);
    mapHead.put("pageSize", pageSize);
    jsonHead = GsonUtils.buildRequestParams(mapHead);
    MyOkHttpUtils.postStringCallBacks(jsonHead, CommonUrl.BASEURL_YIBAN, new MyOkHttpUtilsCallBack() {
        @Override
        public void successCallback(String response, int id) {
            LogUtils.e("getyiBanList: " + response);
        }

        @Override
        public void errorCallback(Call call, Exception e, int id) {
            ToastUtils.ShowToast("获取已办数据-请求失败");
        }
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值