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);
                        }
                    });
                }
            });
    
        }
    }
  • 相关阅读:
    操作系统---学习笔记00
    操作系统---学习笔记0
    2015/07/16入园啦!
    1-1 console的用法
    2.3 js基础--DOM
    1.2 js基础
    1.1 js基础
    信息收集(1)
    Android概述
    从一次失败的比赛经历引发的思考
  • 原文地址:https://www.cnblogs.com/itfenqing/p/6757148.html
Copyright © 2011-2022 走看看