okhttputils Android 一个改善的okHttp封装库使用

Posted HaiyuKing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了okhttputils Android 一个改善的okHttp封装库使用相关的知识,希望对你有一定的参考价值。

上一篇讲了如何在项目中导入OKHttputils库的操作,这一篇主要讲常见请求的写法。

get请求

    public String getPersionType(StringCallback callback)
            throws Exception {
        String result = "";
        OkHttpUtils
                .get()
                .url(getSpcyUrl(context.getString(R.string.get_persion_type_url)))
                .addParams("IS_JSON", "true")
                .addParams("VALUE_OBJES_4_JSON", "jsonMap")
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

 回调

/**
     * 获取用户权限接口的自定义回调函数*/
    public class GetPersionTypeStringCallback extends StringCallback
    {
        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialog("");//显示进度加载框
        }

        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {
            ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again));
            Log.w(TAG,"{onError}e="+e.toString());
        }

        @Override
        public void onResponse(String response, int id)
        {
            Log.e(TAG, "onResponse:response="+response);
            switch (id)
            {
                case 100://http
                    try {
                        if (response != null && !"".equals(response)){
                            //解析
                        }
                        else {
                            ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_null_exception));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    }catch (Exception e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    } finally {
                    }
                    break;
                case 101://https
                    break;
            }
        }
        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.e(TAG, "inProgress:" + progress);
        }
    }

Post请求

    public String Login(String userName, String password,StringCallback callback)
            throws Exception {
        String result = "";
        OkHttpUtils
                .post()
                .url(getSpcyUrl(context.getString(R.string.login_url)))
                .addParams("user.userName", userName)
                .addParams("user.password", password)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
         return result;
    }

 

回调

/**
     * 登录接口的自定义回调函数*/
    public class LoginStringCallback extends StringCallback
    {
        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialog("");//显示进度加载框
        }

        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {
            ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again));
            Log.w(TAG,"{onError}e="+e.toString());
        }

        @Override
        public void onResponse(String response, int id)
        {
            Log.e(TAG, "onResponse:response="+response);
            switch (id)
            {
                case 100://http
                    try {
                        if (response != null && !"".equals(response)){
                            //解析登录信息
                            JSONObject responseObj = new JSONObject(response);
                        }
                        else {
                            ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_null_exception));
                        }
                    } catch (JSONException e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    }catch (Exception e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    } finally {
                    }
                    break;
                case 101://https
                    break;
            }
        }
        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.e(TAG, "inProgress:" + progress);
        }
    }

postString【Json数据】请求

    /**
     * post 提交json数据接口
     */
    public String postJson(PostJsonModel postJsonModel, StringCallback callback){
        String result = "";
        OkHttpUtils
                .postString()
                .url(getSpcyUrl(context.getString(R.string.postjson_url)))
                .content(new Gson().toJson(postJsonModel))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }
技术分享
package com.why.project.okhttputilsdemo.model;

/**
 * Created by HaiyuKing
 * Used
 */

public class PostJsonModel {
    private String title = "";
    private String tic = "";
    private String type = "";

    public String getTic() {
        return tic;
    }

    public void setTic(String tic) {
        this.tic = tic;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}
PostJsonModel

回调【跟post、get请求的回调写法类似】

post提交文件请求

/**
     * post 提交文件接口
     */
    public String postFile(File file, StringCallback callback){
        String result = "";
        OkHttpUtils
                .postFile()
                .url(getSpcyUrl(context.getString(R.string.postfile_url)))
                .file(file)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

回调【跟post、get请求的回调写法类似】

上传单个文件请求

/**
     * 单个文件上传接口
     */
    public String upLoadFile(String fileid, String filepath, String filename,StringCallback callback){
        String result = "";
        OkHttpUtils
                .post()
                .url(getSpcyUrl(context.getString(R.string.upload_file_url)))
                .addFile("uploadUtil.file", filename, new File(filepath))
                .addParams("fileId",fileid)
          .id(100)
         .tag(context)
         .build()
         .execute(callback);
    
return result;
   }

 回调

/**
     * 文件上传接口的自定义回调函数*/
    public class UpLoadFileStringCallback extends StringCallback
    {
        public UpLoadFileStringCallback(){
        }

        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialogUpload("");//显示加载对话框
        }

        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again));
        }

        @Override
        public void onResponse(String response, int id)
        {
            Log.e(TAG, "onResponse:response="+response);
            switch (id)
            {
                case 100://http
                    try {
                        if (response != null && !"".equals(response)){
                            //
                            JSONObject object = new JSONObject(response);
                            if(object.has("result") && object.getString("result").equals("上传成功")){
                                ToastUtil.showShortToastCenter("上传成功");
                            }else{
                                ToastUtil.showShortToastCenter("上传失败,请重试!");
                            }
                        } else {
                            ToastUtil.showShortToastCenter("上传失败,请重试!");
                        }
                    }catch (JSONException e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    }catch (Exception e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    } finally {
                    }
                    break;
                case 101://https
                    break;
            }
        }
        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.e(TAG, "inProgress:" + progress);//inProgress:0.99884826
            tv_result.setText("正在上传:" + (int)(progress * 100)+"%");//模拟显示进度值
            //ProgressWheelDialogUtil.setDialogMsg((int)(progress * 100)+"%");//更改上传进度提示框的进度值
        }
    }

上传多个文件的请求

/**
     * 多个文件上传接口
     */
    public String upLoadFiles(String fileId, List<UploadFilesModel> uploadFilesModelList, StringCallback callback){
        String result = "";

        HashMap<String, File> fileMap = new HashMap<String,File>();
        for(int i=0;i<uploadFilesModelList.size();i++) {
            UploadFilesModel model = uploadFilesModelList.get(i);
            File file = new File(model.getFilePath());
            fileMap.put(model.getFileName(), file);
        }
        OkHttpUtils
                .post()
                .url(getSpcyUrl(context.getString(R.string.upload_file_url)))
                .files("uploadUtil.file",fileMap)
                .addParams("fileId", fileid)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

 

package com.why.project.okhttputilsdemo.model;

/**
 * Created by HaiyuKing
 * Used 上传多个文件的model类
 */

public class UploadFilesModel {
    private String filePath;
    private String fileName;

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
}

 回调

/**
     * 文件上传接口的自定义回调函数*/
    public class UpLoadFilesStringCallback extends StringCallback
    {
        public UpLoadFilesStringCallback(){
        }

        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialogUpload("");//显示加载对话框
        }

        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_again));
        }

        @Override
        public void onResponse(String response, int id)
        {
            Log.e(TAG, "onResponse:response="+response);
            switch (id)
            {
                case 100://http
                    try {
                        if (response != null && !"".equals(response)){
                            //
                            JSONObject object = new JSONObject(response);
                            if(object.has("result") && object.getString("result").equals("上传成功")){
                                ToastUtil.showShortToastCenter("上传成功");
                            }else{
                                ToastUtil.showShortToastCenter("上传失败,请重试!");
                            }
                        } else {
                            ToastUtil.showShortToastCenter("上传失败,请重试!");
                        }
                    }catch (JSONException e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    }catch (Exception e) {
                        ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.login_json_exception));
                    } finally {
                    }
                    break;
                case 101://https
                    break;
            }
        }
        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.e(TAG, "inProgress:" + progress);//inProgress:0.99884826
            tv_result.setText("正在上传:" + (int)(progress * 100)+"%");//模拟显示进度值
            //ProgressWheelDialogUtil.setDialogMsg((int)(progress * 100)+"%");//更改上传进度提示框的进度值
        }
    }

下载文件请求【返回的下载值为文件大小】

    /**
     * 文件下载接口【返回的下载值为文件大小】
     */
    public String downloadFile(String fileid, FileCallBack callback){
        String result = "";
        OkHttpUtils
                .get()
                .url(getSpcyUrl(context.getString(R.string.download_file_url)))
                .addParams("fileid", fileid)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

回调

/**
     * 文件下载接口的自定义回调函数*/
    public class DownLoadFileCallBack extends FileCallBack
    {

        String fileSavepath = "";
        String filename = "";
        String fileSize = "";

        float fileSizeNum = 0.0f;

        /**
         * @param destFileDir
         * @param destFileName
         */
        public DownLoadFileCallBack(String destFileDir,String destFileName,String fileSize) {
            super(destFileDir, destFileName);
            this.fileSavepath = destFileDir;
            this.filename = destFileName;
            this.fileSize = fileSize;

            fileSizeNum = Float.parseFloat(fileSize.substring(0, fileSize.length() - 2));
        }

        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialogUpload("");//显示加载对话框
        }
        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.w(TAG,"{inProgress}progress="+progress);//情况一:显示下载的文件大小,单位是B -1235527.0
            float progressABS = Math.abs(progress);//取正

            DecimalFormat df = new DecimalFormat("#.##");
            double progressKB = progressABS / 1024.0D;//获取KB值
            if (fileSize.contains("MB"))
                progressABS = Float.parseFloat(df.format(progressKB / 1024.0D));//获取MB值
            else
                progressABS = Float.parseFloat(df.format(progressKB));
            Log.e(TAG,"progressABS:" + progressABS);
            Log.e(TAG,"progressABS/fileSizeNum== :" + progressABS/fileSizeNum);

            tv_result.setText("下载进度:" + (int)(progressABS/fileSizeNum * 100)+"%");
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {
            ToastUtil.showShortToast("下载失败");
        }

        @Override
        public void onResponse(File file, int id)
        {
            Log.e(TAG, "onResponse :" + file.getAbsolutePath());
            ToastUtil.showShortToast("下载成功");
        }

    }

下载文件请求【返回的下载值为文件下载的比例值】

    /**
     * 文件下载接口【返回的下载值为文件下载的比例值】
     */
    public String downloadFile2(FileCallBack callback){
        String result = "";
        OkHttpUtils
                .get()
                .url("http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk")
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

回调

/**
     * 文件下载接口的自定义回调函数*/
    public class DownLoadFile2CallBack extends FileCallBack
    {

        String fileSavepath = "";
        String filename = "";

        /**
         * @param destFileDir
         * @param destFileName
         */
        public DownLoadFile2CallBack(String destFileDir,
                                    String destFileName) {
            super(destFileDir, destFileName);
            this.fileSavepath = destFileDir;
            this.filename = destFileName;
        }

        @Override
        public void onBefore(Request request, int id)
        {//showProgressDialogUpload("");//显示加载对话框
        }
        @Override
        public void onAfter(int id)
        {//dismissProgressDialog();//隐藏进度加载框
        }

        @Override
        public void inProgress(float progress, long total, int id)
        {
            Log.w(TAG,"{inProgress}progress="+progress);//情况一:下载进度值为文件的下载比例值 0.4827961
            float progress1 = Math.abs(progress);
            tv_result.setText("下载进度:" + (int)(progress1 * 100)+"%");
        }

        @Override
        public void onError(Call call, Exception e, int id)
        {
            ToastUtil.showShortToast("下载失败");
        }

        @Override
        public void onResponse(File file, int id)
        {
            Log.e(TAG, "onResponse :" + file.getAbsolutePath());
            ToastUtil.showShortToast("下载成功");
        }

    }

同步请求【需要在子线程中执行

/**
     * 模拟同步请求--注销*/
    public String Logout() throws IOException {
        String result = "";
        //同步请求--用于在自定义的thread中执行
        Response response = OkHttpUtils
                .post()
                .url(getSpcyUrl(context.getString(R.string.logout_url)))
                .addParams("IS_JSON", "true")
                .id(100)
                .tag(context)
                .build()
                .execute();
        //execute方法不传入callback即为同步的请求,返回Response对象,需要自己解析
        InputStream responseIs = response.body().byteStream();
        BufferedReader responseBufferedReader = new BufferedReader(new InputStreamReader(responseIs, "utf-8"));
        StringBuilder responseStringBuilder = new StringBuilder();
        while (true)
        {
            String readLine = responseBufferedReader.readLine();
            if (readLine == null)
            {
                break;
            }
            responseStringBuilder.append(readLine);
        }
        responseIs.close();
        result = responseStringBuilder.toString();
        return result;
    }

调用

//模拟同步请求--注销
        btn_synchronize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String logoutStr = LoginLogic.Instance(MainActivity.this).Logout();

                            Message msg = new Message();
                            msg.what = TOAST_SHOW;
                            msg.obj = logoutStr;
                            mHandler.sendMessage(msg);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    /**用于toast提示*/
    private static final int TOAST_SHOW = 18;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TOAST_SHOW:
                    ToastUtil.showShortToast((String)msg.obj);
                    tv_result.setText((String)msg.obj);
                    break;
            }
        }
    };

单个请求添加cookie

    /**
     * 获取接口
     */
    public String getNews(StringCallback callback)
            throws Exception {
        String result = "";
        String SESSION_SERVER_HEAD = "JSESSIONID=";
        String SESSION_SERVER_ID = "9B17276F7C0CA4F309ABA0C93D87A3F8";
        OkHttpUtils
                .get()
                .url(getSpcyUrl(context.getString(R.string.get_news_url)))
                .addHeader("Cookie",SESSION_SERVER_HEAD + SESSION_SERVER_ID)
                .id(100)
                .tag(context)
                .build()
                .execute(callback);
        return result;
    }

获取cookies【用于保存到SharedPreferences中】

    /**获取cookies*/
    public static String getCookiesStr(){
        String cookiesInfo = "";
        CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        if (cookieJar instanceof CookieJarImpl)
        {
            CookieStore cookieStore = ((CookieJarImpl) cookieJar).getCookieStore();
            List<Cookie> cookies = cookieStore.getCookies();
            for(Cookie cookie : cookies){
                cookiesInfo = cookiesInfo + cookie.name() + ":" + cookie.value() + ";";
            }
        }

        return cookiesInfo;
    }

清空cookies

    /**清空cookie缓存*/
    public static void clearCookies()
    {
        CookieJar cookieJar = OkHttpUtils.getInstance().getOkHttpClient().cookieJar();
        if (cookieJar instanceof CookieJarImpl)
        {
            ((CookieJarImpl) cookieJar).getCookieStore().removeAll();
        }
    }

 webview异步cookies

/**
     * Sync Cookie
     */
    public static void syncCookie(Context context, String url){
        try{
            LogUtil.d("Nat: webView.syncCookie.url", url);
            String sessionId = "";
            String domain = "";
            String path = "";

            //获取保存的cookie信息
            String savedCookie = PreferencesUtils.get(context,PreferencesUtils.COOKEY,"").toString();//JSESSIONID:9B17276F7C0CA4F309ABA0C93D87A3F8;
            if(!TextUtils.isEmpty(savedCookie)){
                String[] cookies = savedCookie.split(";");
                for(int i=0;i<cookies.length;i++){
                    if(!TextUtils.isEmpty(cookies[i].trim())){
                        if(cookies[i].trim().contains("JSESSIONID")){
                            String[] cookie = cookies[i].split(":");
                            sessionId = cookie[1].trim();
                        }
                    }

                }

                path = context.getResources().getString(R.string.server_url);
                LogUtil.d("MainActivity", "sessionId="+sessionId);
                LogUtil.d("MainActivity", "path="+path);

                CookieSyncManager.createInstance(context);

                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                cookieManager.removeSessionCookie();// 移除
                cookieManager.removeAllCookie();
                String oldCookie = cookieManager.getCookie(url);
                if(oldCookie != null){
                    LogUtil.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
                }
                //方式一【没有起作用】
                StringBuilder sbCookie = new StringBuilder();
                sbCookie.append(String.format("JSESSIONID=%s",sessionId));
                //ip地址的话应该是不需要设置的,只有在域名的情况下才可以设置
                //sbCookie.append(String.format(";domain=%s", domain));
                sbCookie.append(String.format(";path=%s",path));
                sbCookie.append(String.format(";loginmodel=%s","normal"));
                String cookieValue = sbCookie.toString();
                cookieManager.setCookie(url,cookieValue);

                CookieSyncManager.getInstance().sync();

                String newCookie = cookieManager.getCookie(url);
                if(newCookie != null){
                    LogUtil.d("Nat: webView.syncCookie.newCookie", newCookie);
                }
            }

        }catch(Exception e){
            LogUtil.e("Nat: webView.syncCookie failed", e.toString());
        }
    }

配置HTTPS请求

/**
     * 配置OkhttpClient
     */
    private void initOkHttp() {
        
        CookieJarImpl cookieJar = new CookieJarImpl(new PersistentCookieStore(getApplicationContext()));//修改成自带的cookie持久化,可以解决程序崩溃时返回到
        //ClearableCookieJar cookieJar1 = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));


        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);//设置可访问所有的https网站

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(10000L, TimeUnit.MILLISECONDS)
        .readTimeout(10000L, TimeUnit.MILLISECONDS)
        //配置Log,通过设置拦截器实现,框架中提供了一个LoggerInterceptor,当然你可以自行实现一个Interceptor 
        .addInterceptor(new LoggerInterceptor("TAG"))
        //配置持久化Cookie(包含Session)
        .cookieJar(cookieJar)
        .hostnameVerifier(new HostnameVerifier()
        {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                // TODO Auto-generated method stub
                //return false;
                return true;
            }
        })
        //配置Https
        .sslSocketFactory(sslContext.getSocketFactory())
        .build();
        OkHttpUtils.initClient(okHttpClient);
    }

设置UA【默认为okhttp/3.3】

OkHttpUtils.head().addHeader("User-Agent","mobile");//设置UA,默认为okHttp的版本okhttp/3.3.0

在MyApplication.java中的initOkHttp方法中最后一行添加。

 

以上是关于okhttputils Android 一个改善的okHttp封装库使用的主要内容,如果未能解决你的问题,请参考以下文章

Android 网络请求框架okhttputils报错(okhttp3找不到)

android OkHttpUtils 使用JSON数据作为请求参数

毕加索的艺术——Picasso,一个强大的Android图片下载缓存库,OkHttpUtils的使用,二次封装PicassoUtils实现微信精选

OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据

Android开发复用代码

OkHttpUtils一个专注于让网络请求更简单的框架