一、准备工作

1、build.gradle 配置文件引入 okhttp

dependencies {
	...
    implementation("com.squareup.okhttp3:okhttp:4.10.0")
    implementation 'cn.hutool:hutool-all:5.8.4'

}

使用 viewBinding 注意:顺便加下 buildFeatures

android {
    compileSdk 31
	...
    buildFeatures {
        viewBinding true
    }
}

2、AndroidManifest.xml 配置放开网络权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.luna.apitest">

    <!--  网络权限  -->
    <uses-permission android:name="android.permission.INTERNET" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.APITest">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

二、调用接口

1、布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_show_get"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="40dp"
        android:gravity="center"
        android:hint="通过网络请求获取到的内容"
        android:padding="5dp" />

    <Button
        android:id="@+id/bt_send_get"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="GET发送请求" />

    <TextView
        android:id="@+id/tv_show_post"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="40dp"
        android:gravity="center"
        android:hint="通过网络请求获取到的内容"
        android:padding="5dp" />

    <Button
        android:id="@+id/bt_send_post"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="POST发送请求" />

</LinearLayout>

2、新建单例工具类

object OkHttpUtil {

    fun get(url: String, callback: Callback) {
        Thread {
            val client: OkHttpClient = OkHttpClient.Builder().build()
            val request: okhttp3.Request = okhttp3.Request.Builder()
                .url(url)
                .build()
            client.newCall(request).enqueue(callback)
        }.start()
    }

    fun post(url: String, json: String, callback: Callback) {
        Thread {
            val requestBody: RequestBody =
                json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
            val client: OkHttpClient = OkHttpClient.Builder().build()
            val request: okhttp3.Request = okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .build()
            client.newCall(request).enqueue(callback)
        }.start()
    }
}

3、Activity 调用接口实现

package com.luna.apitest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import cn.hutool.json.JSONObject
import cn.hutool.json.JSONUtil
import com.luna.apitest.databinding.ActivityMainBinding
import com.luna.apitest.util.OkHttpUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //加载布局
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // get接口:按钮点击事件
        binding.btSendGet.setOnClickListener {
            OkHttpUtil.get("https://api.iyk0.com/twqh", object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    runOnUiThread {
                        Runnable {
                            Log.d("MainActivity", "请求失败!")
                        }
                    }
                }

                override fun onResponse(call: Call, response: Response) {
                    val data = response.body?.string().toString()
                    showData(data)
                    Log.d("MainActivity", "获取到的数据为:$data")
                }
            })
        }

        // post接口:按钮点击事件
        val json: String = "{\n" +
                "  \"id\": 0,\n" +
                "  \"category\": {\n" +
                "    \"id\": 0,\n" +
                "    \"name\": \"string\"\n" +
                "  },\n" +
                "  \"name\": \"doggie\",\n" +
                "  \"photoUrls\": [\n" +
                "    \"string\"\n" +
                "  ],\n" +
                "  \"tags\": [\n" +
                "    {\n" +
                "      \"id\": 0,\n" +
                "      \"name\": \"string\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"status\": \"available\"\n" +
                "}"
        binding.btSendPost.setOnClickListener {
            OkHttpUtil.post("https://petstore.swagger.io/v2/pet", json, object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    runOnUiThread {
                        Runnable {
                            Log.d("MainActivity", "请求失败!")
                        }
                    }
                }

                override fun onResponse(call: Call, response: Response) {
                    val data = response.body?.string().toString()
                    showDataPost(data)
                    Log.d("MainActivity", "获取到的数据为:$data")
                }
            })
        }


    }

    private fun showDataPost(data: String) {
        val data: JSONObject = JSONUtil.parseObj(data)
        binding.tvShowPost.text = data.getStr("id")
    }

    private fun showData(data: String) {
        binding.tvShowGet.text = data
    }
}

如存在问题,请在评论区指出留言,感谢!


版权声明:本文为eureka52hz原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/eureka52hz/article/details/125866424