【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(二)

简介: 【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(二)

完整代码示例 :


 

/**
     * OkHttp 同步 Post 请求
     */
    private void httpSynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                          // 使用 Post 方法
                .build();
        // 同步 Get 请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = mOkHttpClient.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String result = null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "result : " + result);
            }
        }).start();
    }





四、OkHttp 异步 Post 请求


OkHttp 同步 Post 请求分为 4 44 个步骤 :


① 首先 , 创建 FormBody 对象 , 设置 Post 请求表单 ;


       // 创建 Post 表单 , 主要用于设置 Post 请求键值对

// 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();

   

② 然后 , 创建 Request 请求对象 , 并传入 FormBody 表单 ;

// Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                          // 使用 Post方法
                .build();


③ 在后 , 创建异步 Post 请求的回调方法 Callback 对象 ;


   

// 创建异步回调
        Callback callback = new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };


④ 最后 , 进行同步 Post 请求 , 注意要在线程中使用同步 Post 方法 ;


 

// 异步 Get 请求
        mOkHttpClient.newCall(request).enqueue(callback);


完整代码示例 :


 

/**
     * OkHttp 异步 Post 请求
     */
    private void httpAsynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                 // 使用 Post 方法
                .build();
        // 创建异步回调
        Callback callback = new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };
        // 异步 Get 请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }






五、完整源代码示例


package com.example.okhttp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.example.okhttp.databinding.ActivityMainBinding;
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 {
    private static final String TAG = "MainActivity";
    /**
     * ViewBinding 类
     * activity_main 布局映射出来的类
     * 该类主要作用是封装组件的获取
     */
    ActivityMainBinding binding;
    /**
     * OkHttp 客户端
     * 注意 : 该类型对象较大, 尽量在应用中创建较少的该类型对象
     * 推荐使用单例
     */
    OkHttpClient mOkHttpClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        mOkHttpClient = new OkHttpClient();
        binding.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //httpSynchronousGet();
                //httpAsynchronousGet();
                //httpSynchronousPost();
                httpAsynchronousPost();
            }
        });
    }
    /**
     * OkHttp 同步 Get 请求
     */
    private void httpSynchronousGet() {
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();
        // 同步 Get 请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = mOkHttpClient.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String result = null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "result : " + result);
            }
        }).start();
    }
    /**
     * OkHttp 异步 Get 请求
     */
    private void httpAsynchronousGet() {
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .get()                          // 使用 Get 方法
                .build();
        // 创建异步回调
        Callback callback = new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };
        // 异步 Get 请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }
    /**
     * OkHttp 同步 Post 请求
     */
    private void httpSynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                 // 使用 Post 方法
                .build();
        // 同步 Get 请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = mOkHttpClient.newCall(request).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String result = null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "result : " + result);
            }
        }).start();
    }
    /**
     * OkHttp 异步 Post 请求
     */
    private void httpAsynchronousPost() {
        // 创建 Post 表单 , 主要用于设置 Post 请求键值对
        FormBody formBody = new FormBody.Builder()
                .add("Key", "Value")
                .build();
        // Request 中封装了请求相关信息
        Request request = new Request.Builder()
                .url("https://www.baidu.com")   // 设置请求地址
                .post(formBody)                 // 使用 Post 方法
                .build();
        // 创建异步回调
        Callback callback = new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                // 请求失败的情况
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 请求成功 , 获取
                String result = response.body().string();
                Log.i(TAG, "result : " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 主线程中执行相关代码
                    }
                });
            }
        };
        // 异步 Get 请求
        mOkHttpClient.newCall(request).enqueue(callback);
    }
}







目录
相关文章
|
9月前
|
缓存
POST 为什么会发送两次请求?
POST 为什么会发送两次请求?
581 0
|
20天前
|
XML 安全 前端开发
post为什么会发送两次请求详解
【6月更文挑战第5天】在Web开发中,开发者可能会遇到POST请求被发送了两次的情况,
29 0
|
2月前
|
JSON 中间件 数据格式
在服务器框架中处理 POST 请求
在服务器框架中处理 POST 请求
|
11月前
|
JSON 前端开发 JavaScript
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)(三)
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)(三)
|
Android开发
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
【OkHttp】OkHttp Get 和 Post 请求 ( 同步 Get 请求 | 异步 Get 请求 | 同步 Post 请求 | 异步 Post 请求 )(一)
1036 0
|
2月前
|
人工智能 前端开发 安全
post为什么会发送两次请求?
post为什么会发送两次请求?
|
8月前
|
JSON 数据格式
OkHttp3发起POST或GET请求
OkHttp3发起POST或GET请求
213 0
|
11月前
|
JSON 前端开发 网络架构
DRF--请求和响应
DRF--请求和响应
|
11月前
|
XML 数据采集 Web App开发
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)(一)
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)
|
11月前
|
缓存 JSON 前端开发
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)(二)
AJAX(GET POST请求、 jQuery axios 发送请求、跨域--cors、请求超时、网络异常、放弃请求、重复发送请求)(二)