Android 中 OkGo 的使用 (封装 OkHttp)

项目介绍

github地址:https://github.com/jeasonlzy/okhttp-OkGo
wiki:https://github.com/jeasonlzy/okhttp-OkGo/wiki

配置

般来说,只需要添加第一个okgo的核心包即可,其余的三个库根据自己的需要选择添加!!!

//必须使用
compile 'com.lzy.net:okgo:3.0.4'

//以下三个选择添加,okrx和okrx2不能同时使用
compile 'com.lzy.net:okrx:1.0.2'
compile 'com.lzy.net:okrx2:2.0.2'  
compile 'com.lzy.net:okserver:2.0.5'

基本get和post请求

get请求:

OkGo.<String>get("https://api.github.com/repos/square/retrofit/contributors")                            // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .cacheKey("cacheKey")            // 设置当前请求的缓存key,建议每个不同功能的请求设置一个
                .cacheMode(CacheMode.NO_CACHE)    // 缓存模式,详细请看缓存介绍
              //  .cacheTime(3000)//缓存时间
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i("get",response.body());
                        tvText.setText(response.body());
                       
                    }

                     @Override
                     public void onError(Response<String> response) {
                         super.onError(response);
                     }
                });

post请求:

OkGo.<String>post("url")
                 .tag(this)
                .cacheKey("cachePostKey")
                .cacheMode(CacheMode.NO_CACHE)
                .params("shopperId", "9356")
                .params("machineId", "5117")
                .params("orderType", "2")
                .params("orderId", "108")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.i("aaa",response.body());
                        Log.i("time2",System.currentTimeMillis()+"s");
                        BorrowRecordInfo borrowRecordInfo = JSON.parseObject(response.body(),BorrowRecordInfo.class);
                        if (borrowRecordInfo != null){
                            tvText.setText(response.body());
                            Toast.makeText(Demo1.this,borrowRecordInfo.getOrder().getNickName(),Toast.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
原文地址:https://www.cnblogs.com/wbyixx/p/12829244.html