okHttp异步请求的回调在UI线程即主线程中执行

942 阅读1分钟

一、okHttp使用
二、在主线程中执行请求回调的方法

一、
1、先在模块的build.gradle–>dependencies中添加依赖

implementation 'com.squareup.okhttp3:okhttp:4.1.0'

2、新建 OkHttpClient对象

OkHttpClient client = new OkHttpClient();

3、构造 Request 对象

Request request = new Request.Builder().url("http://www.baidu.com").get().build();

4、将 Request 对象封装为 Call并执行同步或异步请求

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(@NotNull Call call, @NotNull IOException e) {

    }//发送失败回调函数

    @Override
    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
        final String string = response.body().string();
        Log.i(TAG, "onResponse: "+string);
        runOnUiThread(new Runnable() {    
            @Override    
            public void run() {        
                tvText.setText(string);    
            }
        });
 }});

注:Android3.0 之后已经不允许在主线程中访问网络了,所有异步请求(enqueue)都会新启一个线程,所以在回调函数中使用runOnUiThread使得run()中代码在主线程中执行。