OKhttp的get请求和post请求

本文介绍了一个使用OkHttp进行网络请求的Android应用示例,包括GET和POST请求的实现方式,以及同步请求的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
        }
    }
}



//配置

   compile 'com.squareup.okhttp3:okhttp:3.9.0'
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值