OkHttp的简单实现

首先我们先导入OkHttp的两条依赖

implementation 'com.squareup.okhttp3:okhttp:3.6.0'
implementation 'com.squareup.okio:okio:1.11.0'

为救急写个简单博客。

get 请求:

因为是同步请求,需要另开一条子线程

new Thread(){
    @Override
    public void run() {
        try {
            //创建ok对象
            OkHttpClient okHttpClient = new OkHttpClient();
            //调用方法
            Request request = new Request.Builder().url(“url地址”).build();
            Call call = okHttpClient.newCall(request);
            Response response = call.execute();
            //获取响应体
            String responseMsg = response.body().string();
            Log.d(TAG, "onHttpGetRequest: "+responseMsg);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}.start();

Post请求:

也是同步的请求,要开一条线程

new Thread(){
        @Override
        public void run() {
            try {
            //创建对象
            OkHttpClient okHttpClient = new OkHttpClient();
            //调用方法
            //表单请求体
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("token", "1");
            builder.add("type", "0");
            builder.add("op_code", "");
            builder.add("phone_no", "18301154407");
            FormBody formBody = builder.build();
            Request request = new Request.Builder().method("POST",formBody).url(GETURL_STRING).build();
            Call call = okHttpClient.newCall(request);
            //获取同步请求
                final Response response = call.execute();
                String responseString = response.body().string();
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }.start();

猜你喜欢

转载自blog.csdn.net/liu_qunfeng/article/details/81540770