OKhttp模版

来源:互联网 发布:淘宝直播预告已过期 编辑:程序博客网 时间:2024/05/22 13:57
依赖:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
public class MainActivity extends AppCompatActivity implements View.OnClickListener {        private static final String TAG = "MainActivity";        private static final int RESPONSE_FLAG = 0x123;        private TextView txtShow;        private Button btnGet;        private Button btnPost;        private Button btnSync;        private Handler handler = new Handler() {            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                switch (msg.what) {                    case RESPONSE_FLAG:                        String str = (String) msg.obj;                        txtShow.setText(str);                        break;                }            }        };        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);            initView();            setListener();            Log.i(TAG, "主线程id: " + Thread.currentThread().getId() + " name:" +                    Thread.currentThread().getName());        }        /**         * 设置监听事件         */        private void setListener() {            btnGet.setOnClickListener(this);            btnPost.setOnClickListener(this);            btnSync.setOnClickListener(this);        }        /**         * 初始化视图控件         */        private void initView() {            txtShow = (TextView) findViewById(R.id.txt_show);            btnGet = (Button) findViewById(R.id.btn_okhttp_get);            btnPost = (Button) findViewById(R.id.btn_okhttp_post);            btnSync = (Button) findViewById(R.id.btn_okhttp_sync);        }        @Override        public void onClick(View v) {            switch (v.getId()) {                // Get请求                case R.id.btn_okhttp_get:                    // 1.OKHttpClient对象//                OkHttpClient client = new OkHttpClient();                    OkHttpClient client = new OkHttpClient.Builder().build();                    // 2.Request对象                    final Request request = new Request.Builder()                            // 默认就是get方式                            .get()                            .url("http://www.wuxirui.com/")                            .build();                    // 3.Call对象                    Call call = client.newCall(request);                    // 4.进行网络请求                    call.enqueue(new Callback() {                        // 请求失败时候的回调                        @Override                        public void onFailure(Call call, IOException e) {                            Log.e(TAG, "onFailure: " + e.getMessage());                        }                        // 请求成功时候的回调                        @Override                        public void onResponse(Call call, Response response) throws IOException {//                        Log.i(TAG, "onResponse: " + response.body().string());                            // response.body().string()本质上是读流的操作                            final String text = response.body().string();                            Log.i(TAG, "onResponse: " + text);                            Log.i(TAG, "okhttp 线程id: " + Thread.currentThread().getId() + " name:" +                                    Thread.currentThread().getName());                            // OKHttp获取到数据之后是回调在子线程//                        txtShow.setText(text);                            runOnUiThread(new Runnable() {                                @Override                                public void run() {                                    txtShow.setText(text);                                }                            });                        }                    });                    txtShow.setText("先走这句");                    break;                // Post请求                case R.id.btn_okhttp_post:                    // 1.OkHttpClient对象                    OkHttpClient client2 = new OkHttpClient();                    // 2.提供post请求需要的body对象                    FormBody body = new FormBody.Builder()                            .add("mobile", "15910907758")                            .add("password", "123456")                            .build();                    // 3.Request对象                    Request request2 = new Request.Builder()                            .post(body)                            .url("http://120.27.23.105/user/login")                            .build();                    // 4. Call对象                    Call call2 = client2.newCall(request2);                    // 5.进行网络请求,enqueue方法,是异步请求                    call2.enqueue(new Callback() {                        @Override                        public void onFailure(Call call, IOException e) {                            Log.e(TAG, "onFailure: " + e.getMessage());                        }                        @Override                        public void onResponse(Call call, Response response) throws IOException {                            Log.i(TAG, "onResponse: " + response.body().string());                        }                    });                    break;                case R.id.btn_okhttp_sync:                    new Thread(new Runnable() {                        @Override                        public void run() {                            OkHttpClient client3 = new OkHttpClient();                            Request request3 = new Request.Builder()                                    .get()                                    .url("http://www.wuxirui.com/")                                    .build();                            Call call3 = client3.newCall(request3);                            try {                                // 默认是在当前线程执行的网络请求                                Response response = call3.execute();                                String text = response.body().string();                                Log.i(TAG, "同步: " + text);                                Message msg = handler.obtainMessage();                                msg.what = RESPONSE_FLAG;                                msg.obj = text;                                msg.sendToTarget();                            } catch (IOException e) {                                e.printStackTrace();                            }                        }                    }).start();                    break;            }        }    }
原创粉丝点击