第一次成功使用okhttp

很长时间只是知道okhttp这个网络请求框架很强大,也看了很多技术文章,但是只是懵懵懂懂,不知道该怎么使用。一个东西再强大,不会在项目中使用,一切都是零。
今天,搜索了好多资料,终于在项目中成功使用,很开心,在这里记录一下知识点,便于以后查看。下面记录一下,使用接口回掉进行网络请求的方法。
    public DataProxy(Context context) {
        this.context = context;
    }
    /**
     * 获取缺勤回调接口
     */
    public interface LeaveListListener {
        void onGetLeaveListSucess(String data);
        void onGetLeaveListFailed(boolean success);
    }

    public void getLeaveList( final LeaveListListener listener) {
        String url = BaseApi.API_LEAVE_GETLEAVECOUNT1;//请求的url
        RequestBody body = new FormBody.Builder()//添加参数
                .add("userId", "1ac3")
                .add("gradeCode", "1")
                .add("gradeId","111111")
                .add("month", "3")
                .build();
        Request request = new Request.Builder().url(url)
                .post(body)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onGetLeaveListFailed(false);//失败回调方法
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();//成功请求数据
               listener.onGetLeaveListSucess(data);//成功回调方法

            }
        });
    } 

下面实在activity中调用请求的方法

 dataProxy = new DataProxy(context);//自定义工具类
        dataProxy.getLeaveList(this);

需要导入两个依赖包
okhttp-3.4.1.jar
okio-1.4.0.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值