zoukankan      html  css  js  c++  java
  • 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);
                        }
                    });
                }
            });
    
        }
    }
  • 相关阅读:
    让用户打开你app的位置功能
    函数递归与栈的关系
    公务员考试
    毕达哥拉斯的故事
    OC5_NSMutableString操作
    OC4_NSString操作
    OC_NSString
    OC3_MyRect
    OC6_类方法
    OC5_构造方法与self指针
  • 原文地址:https://www.cnblogs.com/itfenqing/p/6757148.html
Copyright © 2011-2022 走看看