okhttp框架的基本使用(实用)

网络请求测试网址:https://www.httpbin.org

1.首先,android进行网络请求需要申请权限

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

2.在build.gradle中导入Okhttp的依赖库

implementation("com.squareup.okhttp3:okhttp:4.10.0")

3.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/getSync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get同步请求"
        android:textSize="14sp"
        android:gravity="center"
        android:layout_marginTop="200dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button
        android:id="@+id/getAsync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get异步请求"
        android:textSize="14sp"
        android:gravity="center"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/getSync"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button
        android:id="@+id/postSync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post同步请求"
        android:textSize="14sp"
        android:gravity="center"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/getAsync"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button
        android:id="@+id/postAsync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Post异步请求"
        android:textSize="14sp"
        android:gravity="center"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/postSync"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

4.Get同步请求

    //Get同步请求
    public void getSync(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request=new Request.Builder().url("https://www.httpbin.org/get?a=1&b=1").get().build();
                    Call call=client.newCall(request);
                    Response response = call.execute();
                    Log.d(TAG, "getSync: "+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

5.Get异步请求

    //Get异步请求
    public void getAsync(){
        Request request=new Request.Builder().url("https://www.httpbin.org/get?a=1&b=1").get().build();
        Call call=client.newCall(request);
        //异步请求要调用回调  自带子线程
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "getAsync  onFailure: 请求失败");
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "getAsync  onResponse: 请求成功"+response.body().string());
            }
        });
    }

6.Post同步请求

    //Post同步请求
    public void postSync(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //FromBody继承了RequestBody
                    FormBody formBody=new FormBody.Builder().add("a","1").add("b","1").build();
                    //请求内容
                    Request request=new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();
                    //建立连接
                    Call call=client.newCall(request);
                    //执行
                    Response response = call.execute();
                    //输出响应体的内容
                    Log.d(TAG, "postSync: "+response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

7.Post异步请求

    //Post异步请求
    public void postAsync(){
        FormBody formBody=new FormBody.Builder().add("a","1").add("b","1").build();
        Request request=new Request.Builder().url("https://www.httpbin.org/post").post(formBody).build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "postAsync  onFailure: 请求失败"+e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d(TAG, "postAsync  onResponse: 请求成功"+response.body().string());
            }
        });
    }

8.activity中调用

    private OkHttpClient client;
    private static final String TAG="MainActivity";
    private Button getSync,getAsync,postSync,postAsync;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSync=findViewById(R.id.getSync);
        getAsync=findViewById(R.id.getAsync);
        postSync=findViewById(R.id.postSync);
        postAsync=findViewById(R.id.postAsync);

        client = new OkHttpClient();

        //Get同步请求
        getSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSync();
            }
        });
        //Get异步请求
        getAsync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAsync();
            }
        });

        //Post同步请求
        postSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postSync();
            }
        });

        //Post异步请求
        postAsync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                postAsync();
            }
        });
    }

9.测试结果

(1)Get同步请求
在这里插入图片描述

(2)Get异步请求
在这里插入图片描述

(3)Post同步请求
在这里插入图片描述

(4)Post异步请求
在这里插入图片描述

10.响应码:

200-300之间 代表请求成功(与服务器的通信成功,不代表请求的数据也是成功的)
300-400之间 代表重定向
400-500之间 代表服务器错误

到这里就结束啦!欢迎各位伙伴交流以及纠正错误!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值