android kotlin okhttp的封装

每次发请求需要写以下样板代码,封装起来,减少写代码

AndroidManifest.xml 添加网络权限:

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

app/build.gradle

    implementation 'com.squareup.okhttp3:okhttp:4.8.1'
    implementation 'com.google.code.gson:gson:2.8.9'

新建一个工具类 HttpUtil.kt

object HttpUtil {
    fun sendOkHttpRequest(address: String, callback: okhttp3.Callback) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(address)
            .build()
        client.newCall(request).enqueue(callback)
    }
}

使用:

        btn1.setOnClickListener {
            val address = "http://192.168.1.100:3333/index"

            HttpUtil.sendOkHttpRequest(address, object : Callback {
                override fun onResponse(call: Call, response: Response) {
                    // 得到服务器返回的具体内容
                    val responseData = response.body?.string()

                    if (responseData != null) {
                        Log.d("[long] www", responseData)
                    }
                }
                override fun onFailure(call: Call, e: IOException) {
                    // 在这里对异常情况进行处理
                }
            })
        }

你可能感兴趣的:(android,android,okhttp,kotlin)