1集成nohttp
1在build.gradle(app)中dependencies{}里面添加 。
implementation ‘com.yanzhenjie.nohttp:nohttp:1.1.11’
implementation ‘com.yanzhenjie.nohttp:okhttp:1.1.11’
2新建一个MyApplication 继承自Application 在onCreate()里面初始化nohttp框架(如果项目中已经有了自定义的Application,可以在对应里面做初始化操作,不用重新创建,可略过步骤3) 代码如下。
 public class MyApplication extends Application {
    private static MyApplication app;
    public static boolean canShow = true;
    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        initNet();
    }
    public static Application getAppInstance() {
        return app;
    }
    private void initNet() {
        // 初始化nohttp 网络框架
        InitializationConfig nohttpConfig = InitializationConfig.newBuilder(MyApplication.getAppInstance())
                // 设置全局连接超时时间,单位毫秒,默认10s。
                .connectionTimeout(30 * 1000)
                // 设置全局服务器响应超时时间,单位毫秒,默认10s。
                .readTimeout(30 * 1000)
                // 配置缓存,默认保存数据库DBCacheStore,保存到SD卡使用DiskCacheStore。
                .cacheStore(
                        new DBCacheStore(this).setEnable(true) // 如果不使用缓存,设置setEnable(false)禁用。
                )
                // 配置Cookie,默认保存数据库DBCookieStore,开发者可以自己实现。
                .cookieStore(
                        new DBCookieStore(this).setEnable(false) // 如果不维护cookie,设置false禁用。
                )
                // 配置网络层,URLConnectionNetworkExecutor,如果想用OkHttp:OkHttpNetworkExecutor。
                .networkExecutor(new OkHttpNetworkExecutor())
                // 全局通用Header,add是添加,多次调用add不会覆盖上次add。
                .retry(3) // 全局重试次数,配置后每个请求失败都会重试x次。
                .build();
        NoHttp.initialize(nohttpConfig);
        //日志
        Logger.setDebug(true);// 开启NoHttp的调试模式, 配置后可看到请求过程、日志和错误信息。
        Logger.setTag("NoHttpSample");// 打印Log的tag。
    }
}
3在AndroidMainifest.xml里面的application里添加上一步MyApplication的引用
<application
...
    android:name=".MyApplication"
    ...
>
</application>
2使用
1在项目中复制对应文件HttpRequestTool到放工具类的文件夹。
2设置对应的baseUrl ,在HttpRequestTool里面,可根据项目的不同,灵活变动。
3基本的网络请求,直接调用request方法 其中请求地址 url, 请求参数 Map<String,Object> params, 对应的context ,网络请求的tag, 回调 callBack 示例如下。
        Map<String, Object> pramas = new HashMap<>();
        pramas.put("limit", "20");
        pramas.put("page", 1);
        pramas.put("id", "1");
        HttpRequestTool.getInstance().request("Users/index", pramas, MainActivity.this, 1, new HttpRequestTool.CallBack() {
            @Override
            public void onResponseSuccess(String data, int tag) {
                Toast ts = Toast.makeText(getBaseContext(),data,Toast.LENGTH_LONG);
                ts.show();
            }
            @Override
            public void onResponseFailed(Response<JSONObject> response, int tag) {
                Toast ts = Toast.makeText(getBaseContext(),"请求失败",Toast.LENGTH_LONG);
                ts.show();
            }
        });
HttpRequestTool对应源码如下
package com.example.httprequesttooldemo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Environment;
import android.widget.ImageView;
import android.widget.Toast;
//import com.bumptech.glide.Glide;
//import com.bumptech.glide.load.engine.DiskCacheStrategy;
//import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.yanzhenjie.nohttp.*;
//import com.juying.photographer.base.BaseActivity;
//import com.juying.photographer.base.LoginActivity;
//import com.juying.photographer.base.UserLoginBean;
//import com.juying.photographer.fragment.mine.bean.UsercentersResposesBean;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.OnResponseListener;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.RequestQueue;
import com.yanzhenjie.nohttp.rest.Response;
//import org.devio.takephoto.app.TakePhoto;
//import org.devio.takephoto.compress.CompressConfig;
//import org.devio.takephoto.model.CropOptions;
//import org.devio.takephoto.model.LubanOptions;
//import org.devio.takephoto.model.TakePhotoOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class HttpRequestTool {
    ///网络请求地址
//    public static String imgBaseUrl = "http://192.168.8.88:8083";
    public static String imgBaseUrl = "http://49.4.25.106";
    String baseUrl = imgBaseUrl + "/v2/";
    ///网络请求
    private Request request;
    public RequestQueue mQueue = NoHttp.newRequestQueue(1);
    ///当前网络请求的context
    public Context context;
    ////网络请求的回调
    public  CallBack callBack;
    ///json转模型框架
    public Gson gson = new Gson();
    private HttpRequestTool() {
    }
    private static HttpRequestTool singleton;
    public static synchronized HttpRequestTool getInstance() {
        if (singleton == null) {
            singleton = new HttpRequestTool();
        }
        return singleton;
    }
    ///保存用户登录数据
    public void saveUserLoginInfo(String json ,Context context1){
        SharedPreferences settings = context1.getSharedPreferences("UserLoginInfo", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("UserLoginInfo",json);
        editor.commit();
    }
    ///保存用户名
    public void  saveUserName(String userName,Context context1){
        SharedPreferences settings = context1.getSharedPreferences("userName", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("userName",userName);
        editor.commit();
    }
    ///获取用户名
    public String getUserName(Context context1){
        SharedPreferences sharedPreferences= context1.getSharedPreferences("userName", Context .MODE_PRIVATE);
        String data=sharedPreferences.getString("userName","");
        return data;
    }
    ///保存用户信息
    public void  saveUserInfo(String userInfo,Context context1){
        SharedPreferences settings = context1.getSharedPreferences("userInfo", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("userInfo",userInfo);
        editor.commit();
    }
    ///加载网络图片
//    public void setImageSrcWith(ImageView imageView,String url,Context context){
////        if (url==null||url.equals("")){
////
////        }
//        RequestOptions options = new RequestOptions()
//                .placeholder(R.mipmap.logo)
//                .error(R.mipmap.default_img)
//                .diskCacheStrategy(DiskCacheStrategy.NONE);
//        Glide.with(context).load(imgBaseUrl+url).apply(options).into(imageView);
//    }
    ///选取相册(limit最多选几张,isCrop是否剪裁,height,width宽高比(如果isCrop,则不能为空))
//    public void pickBySelectPhoto(TakePhoto takePhoto,int limit,boolean isCrop,int height,int width){
//        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        Uri imageUri = Uri.fromFile(file);
//
//        ///压缩
//        LubanOptions option = new LubanOptions.Builder().setMaxHeight(800).setMaxWidth(800).setMaxSize(1000000).create();
//        CompressConfig config;
//        config = CompressConfig.ofLuban(option);
//        ///压缩后,是否保存原图
//        config.enableReserveRaw(false);
//        ///显示进度条
//        boolean showProgressBar = true;
//        takePhoto.onEnableCompress(config, showProgressBar);
//
//        ///使用自带的相册
//        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
//        builder.setCorrectImage(true);
//        takePhoto.setTakePhotoOptions(builder.create());
//
//        ///最多选几张
////        int limit = 6;
//
//        ///剪裁
//
//
//        if (isCrop) {
//
//            ///剪裁工具,是否自带
//            boolean withWonCrop = true;
//
//            CropOptions.Builder builder1 = new CropOptions.Builder();
//            ///宽高比
////        int height = 300;
////        int width = 200;
//            builder1.setAspectX(width).setAspectY(height);
//
//            builder1.setWithOwnCrop(withWonCrop);
//            CropOptions cropOptions = builder1.create();
//            takePhoto.onPickMultipleWithCrop(limit, cropOptions);
//        }else {
//            takePhoto.onPickMultiple(limit);
//
//        }
//
//    }
//
//
//    ///选取拍照(limit最多选几张,isCrop是否剪裁,height,width宽高比(如果isCrop,则不能为空))
//    public void pickByTake(TakePhoto takePhoto,int limit,boolean isCrop,int height,int width){
//        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        Uri imageUri = Uri.fromFile(file);
//
//        ///压缩
//        LubanOptions option = new LubanOptions.Builder().setMaxHeight(800).setMaxWidth(800).setMaxSize(1000000).create();
//        CompressConfig config;
//        config = CompressConfig.ofLuban(option);
//        ///压缩后,是否保存原图
//        config.enableReserveRaw(false);
//        ///显示进度条
//        boolean showProgressBar = true;
//        takePhoto.onEnableCompress(config, showProgressBar);
//
//        ///使用自带的相册
//        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
//        builder.setCorrectImage(true);
//        takePhoto.setTakePhotoOptions(builder.create());
//
//        ///最多选几张
////        int limit = 6;
//
//        ///剪裁
//
//
//        if (isCrop) {
//
//            ///剪裁工具,是否自带
//            boolean withWonCrop = true;
//
//            CropOptions.Builder builder1 = new CropOptions.Builder();
//            ///宽高比
////        int height = 300;
////        int width = 200;
//            builder1.setAspectX(width).setAspectY(height);
//
//            builder1.setWithOwnCrop(withWonCrop);
//            CropOptions cropOptions = builder1.create();
//            takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
//        }else {
//            takePhoto.onPickFromCapture(imageUri);
//
//        }
//
//    }
    ///网络请求封装
    public void request(String url, Map<String,Object> params, Context context , int tag, CallBack callBack){
        this.context = context;
        if (url == null){
            url = "";
        }
        request = NoHttp.createJsonObjectRequest(baseUrl +url, RequestMethod.POST);
        if (params == null){
            params = new HashMap<String,Object>();
        }
//        UserLoginBean userinfo = getUserLoginInfo(context);
//        if (userinfo !=null){
//            ///添加token
//            params.put("token",userinfo.getData().getToken());
//        }else {
//            params.put("token","0");
//
//        }
        request.add(params);
        mQueue.add(tag, request, responseListener);
        this.callBack = callBack;
    }
    // 回调接口
    public interface CallBack {
        void onResponseSuccess(String data, int tag);
        void onResponseFailed(Response<JSONObject> response, int tag);
    }
    ///网络请求回调,监听
    OnResponseListener<JSONObject> responseListener = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int what) {
            try{
//                BaseActivity activity = (BaseActivity)context;
//                activity.showLoading();
            }catch (Exception error){}
//            if (myWaitDialog == null) {
//                if (context ==null){return;}
//                myWaitDialog = new MyWaitDialog(context);
//                myWaitDialog.show();
//            } else {
//                myWaitDialog.show();
//            }
        }
        ///成功回调
        @Override
        public void onSucceed(int what, Response<JSONObject> response) {
            try{
//                BaseActivity activity = (BaseActivity)context;
//                activity.closeLoading();
            }catch (Exception error){}
            String json = response.get().toString();
            try{
                String status = response.get().getString("code");
                String msg = response.get().getString("message");
                if (status.equals("200")){
                    ///成功回调
                    callBack.onResponseSuccess(json,what);
                }else {
                    ///给出错误提示
                    Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                    toast.show();
                    if (status.equals("309")){
                        ///token错误,跳登录,
//                        saveUserName("",context);
                        saveUserLoginInfo("",context);
//                        isLogin(context);
                    }
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }
        ///失败回调
        @Override
        public void onFailed(int what, Response<JSONObject> response) {
            callBack.onResponseFailed(response,what);
        }
        ///完成回调
        @Override
        public void onFinish(int what) {
//            try{
//                BaseActivity activity = (BaseActivity)context;
//                activity.closeLoading();
//            }catch (Exception error){}
            //            callBack.onResponseFailed(null,what);
        }
    };
}
来源:CSDN
作者:weixin_36672783
链接:https://blog.csdn.net/weixin_36672783/article/details/104643112