OkHttpClient

一.OkHttpClient
详细简洁:https://github.com/hongyangAndroid/okhttputils

 

二.基本示例(Get请求)

public class MainActivity extends Activity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.content);
        Log.e("Thread", Thread.currentThread().getId() + "");
        getContent();
    }

    private void getContent(){
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            // 异步获取
            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                // 子线程中
                if( Thread.currentThread().getId() ==
                        Looper.getMainLooper().getThread().getId() ){
                    Log.d("线程", "Main Thread");
                }else{
                    Log.d("线程", "Not Main Thread");
                }

                final String res = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中
                        if( Thread.currentThread().getId() ==
                                Looper.getMainLooper().getThread().getId() ){
                            Log.d("线程", "Main Thread");
                        }
                        tv.setText(res);
                    }
                });
            }
        });

    }
}

 

posted @ 2017-04-24 15:38  rorshach  阅读(567)  评论(0编辑  收藏  举报