OkHttp3 接口回调 UI线程

Android studio 依赖

    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    compile 'com.squareup.okio:okio:1.11.0'

添加网络权限

    <uses-permission android:name="android.permission.INTERNET"/>

Ansy方法

public class AsynHttp {
    OkHttpClient mOkHttpClient;
    /**
     * Ansy
     * @param Url 访问链接
     * @param ansyCallback 回调接口
     */
    public void getAsynHttp(final String Url,final AnsyCallback ansyCallback){
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                ansyCallback.AnsyLoader((T)msg.obj,Url);
            }
        };
        mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Url);
        requestBuilder.method("GET",null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (null != response.cacheResponse()) {
                    String str = response.cacheResponse().toString();
                    Message message = handler.obtainMessage(0,str);
                    handler.sendMessage(message);
                    Log.i("wangshu", "cache---" + str);
                } else {
                    String d = response.body().string();
                    String str = response.networkResponse().toString();
                    Message message = handler.obtainMessage(0,d);
                    handler.sendMessage(message);
                    Log.i("wangshu", "network---" + str);
                }
            }
        });
    }
    //接口
    public interface AnsyCallback {
        public void AnsyLoader(T loder,String Url);
    }
}

调用Ansy方法

AsynHttp<String> asynHttp = new AsynHttp<>();
        asynHttp.getAsynHttp("http://www.baidu.com", new AsynHttp.AnsyCallback<String>() {
            @Override
            public void AnsyLoader(String loder, String Url) {
                //此处UI线程
                TextView textView = (TextView)findViewById(R.id.m);
                textView.setText(loder);
            }
        });

你可能感兴趣的:(Android)