OkHttp的同步请求和异步请求


接下来就是代码展示了

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";

    private static final int RESPONSE_FLAG = 0x123;

    private Button butget;
    private Button butpost;
    private Button buttong;
    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;
                    textview.setText(str);
                    break;
            }
        }
    };
    private TextView textview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setListent();

    }
     //设置监听
    private void setListent() {
        butget.setOnClickListener(this);
        butpost.setOnClickListener(this);
        buttong.setOnClickListener(this);
    }
    //初始化控件
    private void initView() {
        textview = (TextView) findViewById(R.id.text);
        butget = (Button) findViewById(R.id.but_get);
        butpost = (Button) findViewById(R.id.but_post);
        buttong = (Button) findViewById(R.id.but_tong);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // Get请求
            case R.id.but_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() {
                                textview.setText(text);
                            }
                        });

                    }
                });

                textview.setText("先走这句");

                break;
//----------------------------------------------------------------------------------------------
            // Post请求
            case R.id.but_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.but_tong:
                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;
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值