• 23、Android -- OKHttp3 基础学习


    说明

    OKHttp3 主要是一个网络请求

    • 网络请求方式一般为PUT,DELETE,POST,GET等。常用的是get、post
    • 文件的上传下载
    • 加载图片(内部会图片大小自动压缩)
    • 支持请求回调,直接返回对象、对象集合
    • 支持session的保持

    示例

    1、添加依赖库、和网络权限

    • 依赖库
      build.gradle
        // okhttp3 的依赖库
        implementation 'com.squareup.okhttp3:okhttp:4.9.0'
    
    • 1
    • 2

    网络权限
    AndroidManifest.xml

    	<uses-permission android:name="android.permission.INTERNET"/>
    
    • 1

    2、布局文件

    主要用于示例中按钮处方请求
    res/layout/activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">
        <Button
            android:id="@+id/btn_mian_one"
            android:text="Get同步请求"
            android:onClick="GetSyn"
            android:layout_width="200dp"
            android:layout_height="50dp"
            />
        <Button
            android:id="@+id/btn_mian_two"
            android:text="Get异步请求"
            android:onClick="GetAsync"
            android:layout_width="200dp"
            android:layout_height="50dp"
            />
        <Button
            android:id="@+id/btn_mian_three"
            android:text="Post同步请求"
            android:onClick="PostSyn"
            android:layout_width="200dp"
            android:layout_height="50dp"
            />
        <Button
            android:id="@+id/btn_mian_four"
            android:text="post异步请求"
            android:onClick="PostAsync"
            android:layout_width="200dp"
            android:layout_height="50dp"
            />
    </LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    网络请求

    1、公共

    主要各种请求提取相同代码
    定义 okHttpClient

    private OkHttpClient okHttpClient;
    
    • 1

    实例化

    okHttpClient = new OkHttpClient();
    
    • 1

    2、Get同步请求

     // get 同步步请求
        public void GetSyn(View view) {
            Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
            Call call = okHttpClient.newCall(request);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response response = call.execute();
                        Log.e(TAG, "GetSyn: " +response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    **3、Get异步请求 **

    // get 异步请求
        public void GetAsync(View view) {
            Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "GetAsync: " +e);
                }
    
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.e(TAG, "GetAsync: " +response.body().string());
                }
            });
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    备注1
    Get的同步、异步大部分很相似。
    1、第一步都是-创建OkHttpClient对象(公共中创建的)
    2、第二步都是-通过Request.Builder来创建Request对象
    3、第三步都是-创将抽象Call 执行请求的对象

     		Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
            Call call = okHttpClient.newCall(request);
    
    • 1
    • 2

    区别在于
    4、第四步的区别:
    同步:用call.execute();执行,并用Response接收响应
    异步:call.enqueue()
    5、注意问题:同步代码一般单开线程,避免时间过程

    备注2

    • Reques:该t对象是http请求的抽象对象(包括请求地址,请求方法,请求头,请求体等内容)。通常用Request.Builder来创建该对象。通过request对象的url,method,headers,body等方法能够获取到请求的对应信息。
    • Response对象是http响应的抽象对象(包括响应头,响应体等内容)。
    • Call对象抽象的是一个正在准备执行的请求

    Post 同步请求

     // post 同步请求
        public void PostSyn(View view) {
            FormBody formBody = new FormBody.Builder().add("wd","12")
                    .build();
            Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
            Call call = okHttpClient.newCall(request);
            new Thread(){
                @Override
                public void run() {
    
                    try {
                        Response response = call.execute();
                        Log.e(TAG, "PostAsync: " +response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }.start();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    Post 异步请求

    // post 异步请求
        public void PostAsync(View view) {
            FormBody formBody = new FormBody.Builder().add("wd","12")
                    .build();
            Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
    
                }
    
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.e(TAG, "PostAsync: "+response.body().string());
                }
            });
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    备注3
    Post 的同步和异步相差不多,同“备注1”

    备注4
    get 和post的同步代码也很相似
    区别主要在于post 需要通过FormBody.Builder()创建表单参数。然后才可以传给Request。
    其他的步骤基本相似
    同理,get 和post的异步代码一样

    最终代码java/com/pha/four/MainActivity.java

    package com.pha.four;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    
    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";
        private OkHttpClient okHttpClient;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            okHttpClient = new OkHttpClient();
        }
        // get 同步步请求
        public void GetSyn(View view) {
            Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12")
                    .build();
            Call call = okHttpClient.newCall(request);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Response response = call.execute();
                        Log.e(TAG, "GetSyn: " +response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        // get 异步请求
        public void GetAsync(View view) {
            Request request = new Request.Builder().url("https://www.baidu.com/s?wd=12").build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.e(TAG, "GetAsync: " +e);
                }
    
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.e(TAG, "GetAsync: " +response.body().string());
                }
            });
        }
        // post 同步请求
        public void PostSyn(View view) {
            FormBody formBody = new FormBody.Builder().add("wd","12")
                    .build();
            Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
            Call call = okHttpClient.newCall(request);
            new Thread(){
                @Override
                public void run() {
    
                    try {
                        Response response = call.execute();
                        Log.e(TAG, "PostAsync: " +response.body().string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        // post 异步请求
        public void PostAsync(View view) {
            FormBody formBody = new FormBody.Builder().add("wd","12")
                    .build();
            Request request = new Request.Builder().url("https://www.baidu.com/s").post(formBody).build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
    
                }
    
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    Log.e(TAG, "PostAsync: "+response.body().string());
                }
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
  • 相关阅读:
    【机器学习】21天挑战赛学习笔记(四)
    LoRa和LoRaWAN有什么区别?工业网关能用吗?
    buildadmin+tp8表格操作(4) Table组件,baTable类和 elementplus中的属性关系
    Docker绑定CPU
    STM32+ MAX30102通过指尖测量心率+血氧饱和度
    [数据集][图像分类]茶叶叶子病害分类数据集304张4类别
    OSPF的7大状态和5大报文详讲
    2022DAMA数据治理最佳培训机构奖
    C++新经典10--vector以及其使用
    pytest 测试框架
  • 原文地址:https://blog.csdn.net/u013059089/article/details/126004620