OkHttpUtils的常规使用

简介: 首先在app/build.gradle中导入okhttputils

首先在app/build.gradle中导入okhttputils


dependencies {

   implementation 'com.zhy:okhttputils:2.6.2'

}


如果请求头中含有中文请进行URLEncoder.encode(deviceBrand, "utf-8")

图片上传


public static void upLoadToServer(Context context,String url ,String filepath, final HttpCallBackListener listener) {
    if (CheckNetUtil.isNetworkAvailable(context)) {
        File file = new File(filepath);
        if (!file.exists())
        {
            MyToast.showMessage("文件不存在,请修改文件路径");
            return;
        }
        String filename = file.getName();
        Map<String, String> params = new HashMap<>();
        Map<String, String> headers = getHeadsMap(context);
        headers.put("Content-Disposition","form-data;filename=" + filename);
        OkHttpUtils.post()
                .addFile("mFile", filename, file)
                .url(url)
                .params(params)
                .headers(headers)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        listener.onError("");
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        listener.onSuccess(MStringUtils.isNullOrEmpty(response)?"":response);
                    }
                });
    }


import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import com.youpinwallet.ypw.app.MyAppLication;
import com.youpinwallet.ypw.app.borrow.activity.AlreadyRegisterActivity;
import com.youpinwallet.ypw.bean.HttpResponseBean;
import com.youpinwallet.ypw.bean.TokenBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import okhttp3.Call;
/**
 * Created by Administrator on 2017/4/26.
 */
public class PackOkHttpUtils {
    public PackOkHttpUtils() {
    }
    /**
     * 网络请求
     *
     * @param isPost   true Post false Get
     * @param isDialog true Dialog
     * @param context  context
     * @param url      url
     * @param map      参数
     * @param listener 回调
     */
    public static void getHttpRequest(final boolean isPost, final boolean isDialog, Context context, String url, Map<String, String> map, final HttpCallBackListener listener) {
        map.put("version", CommonParamsUtil.getVersion(context));
        if (isPost) {
            postHttp(context, url, map, listener, isDialog);
        } else {
            getHttp(context, url, map, listener, isDialog);
        }
    }
    public static void getHttpRequestion(final boolean isDialog, Context context, String url, Map<String, String> map, final HttpCallBackListener listener) {
        getHttp(context, url, map, listener, isDialog);
    }
    public interface HttpCallBackListener {
        //请求成功
        void onSuccess(String response);
        //请求失败
        void onError(String response);
    }
    private static void getHttp(final Context context, final String url, final Map<String, String> map, final HttpCallBackListener listener, final boolean isDialog) {
        if (isDialog) {
            NewDialogUtils.setNewDialog(context);
        }
        if (CheckNetUtil.isNetworkAvailable(context)) {
            OkHttpUtils.get()
                    .url(url)
                    .headers(getHeadsMap(context))
                    .params(map)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            NewDialogUtils.dismissNewDialog();
                            listener.onError(e.getMessage());
                        }
                        @Override
                        public void onResponse(String response, int id) {
                            NewDialogUtils.dismissNewDialog();
                            try {
                                HttpResponseBean httpResponseBean = JsonUtils.fromJson(response, HttpResponseBean.class);
                                if (httpResponseBean.getCode() == 50000)//token失效
                                {
                                    getToken(false, isDialog, context, url, map, listener);
                                } else if (httpResponseBean.getCode() == 60000)//RefreshiToken失效
                                {
                                    intentLogin(context);
                                } else {
                                    listener.onSuccess(response);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            NewDialogUtils.dismissNewDialog();
            MyToast.showMessage("请确保网络畅通");
        }
    }
    private static void getToken(final boolean isPost, final boolean isDialog, final Context context, final String url, final Map<String, String> map, final HttpCallBackListener listener) {
        if (isDialog) {
            NewDialogUtils.setNewDialog(context);
        }
        if (CheckNetUtil.isNetworkAvailable(context)) {
            OkHttpUtils.get()
                    .url(ApiUtils.LIGNTING_LOAN_TOKEN_URL)
                    .headers(getTokenHeadsMap())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            NewDialogUtils.dismissNewDialog();
                        }
                        @Override
                        public void onResponse(String response, int id) {
                            NewDialogUtils.dismissNewDialog();
                            try {
                                TokenBean tokenBean = JsonUtils.fromJson(response, TokenBean.class);
                                if (tokenBean.getCode() == Constant.HTTP_SUCCESS)//token失效
                                {
                                    getHttpRequest(isPost, isDialog, context, url, map, listener);
                                } else {
                                    intentLogin(context);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            NewDialogUtils.dismissNewDialog();
        }
    }
    private static void postHttp(final Context context, final String url, final Map<String, String> map, final HttpCallBackListener listener, final boolean isDialog) {
        if (isDialog) {
            NewDialogUtils.setNewDialog(context);
        }
        if (CheckNetUtil.isNetworkAvailable(context)) {
            OkHttpUtils.post()
                    .url(url)
                    .headers(getHeadsMap(context))
                    .params(map)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            NewDialogUtils.dismissNewDialog();
                            listener.onError(e.getMessage());
                        }
                        @Override
                        public void onResponse(String response, int id) {
                            NewDialogUtils.dismissNewDialog();
                            try {
                                HttpResponseBean httpResponseBean = JsonUtils.fromJson(response, HttpResponseBean.class);
                                if (httpResponseBean.getCode() == 50000)//token失效
                                {
                                    getToken(true, isDialog, context, url, map, listener);
                                } else if (httpResponseBean.getCode() == 60000)//RefreshiToken失效
                                {
                                    intentLogin(context);
                                } else {
                                    listener.onSuccess(response);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            NewDialogUtils.dismissNewDialog();
        }
    }
    private static void intentLogin(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }
    public static HashMap<String, String> getHeadsMap(Context context) {
        HashMap<String, String> headsMap = new HashMap<>();
        return headsMap;
    }
    public static HashMap<String, String> getTokenHeadsMap() {
        HashMap<String, String> headsMap = new HashMap<>();
        return headsMap;
    }
}
相关文章
|
Java 网络安全 Maven
简记:一个flutter构建错误A problem occurred configuring project ‘:smart_auth‘. > Could not res
简记:一个flutter构建错误A problem occurred configuring project ‘:smart_auth‘. > Could not res
888 0
|
8月前
|
Java Android开发
Android背景颜色滑动渐变效果(上下滑动,左右滑动)
本文分享了一种通过ScrollView实现滑动变色效果的简单方法。主要步骤包括:1) 在布局中添加ScrollView并确保内容可滑动;2) 获取屏幕高度;3) 获取控件高度;4) 使用GradientDrawable设置渐变颜色;5) 根据控件与屏幕高度比例动态调整颜色数量。示例代码展示了如何在滑动时根据比例改变背景颜色,实现流畅的视觉效果。
238 0
|
小程序 数据可视化 机器人
分享72个商务商城PHP源码,总有一款适合你
分享72个商务商城PHP源码,总有一款适合你
1502 3
|
8月前
|
XML 语音技术 Android开发
Android中TextToSpeech的使用
本文介绍了在Android开发中使用TextToSpeech(TTS)实现语音合成的功能。通过实例代码展示了TTS的初始化、语言设置、语音播放及队列模式的选择,并提供了将语音保存为音频文件的方法。项目中包含一个简单的按钮触发朗读功能,适合初学者学习和实践。代码示例完整,涵盖Activity生命周期管理与XML布局设计。
556 4
|
搜索推荐 Java 开发者
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException 问题处理
【5月更文挑战第14天】org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException 问题处理
5577 1
|
JSON API 数据格式
postman如何发送json请求其中file字段是一个图片
postman如何发送json请求其中file字段是一个图片
579 4
|
easyexcel Java API
Apache POI、EasyPoi、EasyExcel 三种区别,如何选择
Apache POI、EasyPoi、EasyExcel 三种区别,如何选择
2279 0
|
安全 Java
Java的线程同步与通信:深入理解wait、notify和synchronized
Java的线程同步与通信:深入理解wait、notify和synchronized
342 0

热门文章

最新文章