Android okhttp3 框架请求连接等异步操作

25 篇文章 0 订阅

Android okhttp3 框架请求连接等异步操作

自定义回调接口:

public interface MyOkhttp3Callback {
        /**
         * Called when the request could not be executed due to cancellation, a connectivity problem or
         * timeout. Because networks can fail during an exchange, it is possible that the remote server
         * accepted the request before the failure.
         */
       void onFailure(Exception e);

       void onResponse(String htmlString);
}

网络请求:

private void getAsyncOkHttp3Callback(final String urlStr, MyOkhttp3Callback callback) {
    try {
        //1.声名okhttp客户端
        OkHttpClient okHttpClient = new OkHttpClient();

        //2.设置请求方式,设置请求参数
        Request request = new Request.Builder().get().url(urlStr).build();

        //注意区别,同步是这样的:okHttpClient.newCall(request).execute();
        okHttpClient.newCall(request).enqueue(new Callback() {
            //异步
            @Override //请求数据失败的回调
            public void onFailure(Call call, IOException e) {
                callback.onFailure(e);

            }

            @Override //请求数据成功的回调,子线程中运行的  可以判断下状态码 response.code()
            public void onResponse(Call call, Response response) throws IOException {

                byte[] bytes = response.body().bytes();//获得byte[]

                if (bytes.length == 0 || bytes == null) {
                   //根据byte数组长度为0判断

                    callback.onFailure(new Exception("获取结果为空"));
                } else {

                    String responseStr= new String(bytes, "UTF-8");

                    callback.onResponse(responseStr);
                }
            }
        });
    } catch (Exception e) {
        Log.e("getAsyncOkHttp3", " getAsyncOkHttp has Exception:" + e.getMessage());
        callback.onFailure(e);
    }
}

调用如下

getAsyncOkHttp3Callback(urlStr, new MyOkhttp3Callback() {

    @Override
    public void onFailure(Exception e) {
        // TODO 失败后相关提示或展示
    }

    //请求成功执行的方法
    @Override
    public void onResponse(String response) {

           // 异步调用的回调函数是在子线程当中的,因为需要用Handler或者runOnUiThread来更新UI
        xxxActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // TODO 成功后获取数据进一步操作

                }
            });

    }
});

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值