📜  okhttp 依赖 - Kotlin (1)

📅  最后修改于: 2023-12-03 15:03:21.585000             🧑  作者: Mango

OkHttp 依赖 - Kotlin

简介

OkHttp 是一个高效,可靠的 HTTP/HTTPS 客户端。它使用了连接池技术,支持同步和异步请求方式,自动重试失败的请求,以及通过拦截器拦截和修改请求。它还支持流式 API 和流读写,以及自定义验证和协议。

本文主要介绍如何在 Kotlin 项目中使用 OkHttp 依赖。

安装

在项目的 Gradle 文件中添加如下依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.1'
    // 如果需要支持 HTTP/2 协议,则需要添加下面的依赖
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.9.1'
}
使用
发送同步请求
val client = OkHttpClient()

val request = Request.Builder()
    .url("http://www.example.com")
    .build()

val response = client.newCall(request).execute()

if (response.isSuccessful) {
    val body = response.body?.string()
    // 处理返回结果
} else {
    // 处理请求失败的情况
}
发送异步请求
val client = OkHttpClient()

val request = Request.Builder()
    .url("http://www.example.com")
    .build()

client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        // 处理请求失败的情况
    }

    override fun onResponse(call: Call, response: Response) {
        if (response.isSuccessful) {
            val body = response.body?.string()
            // 处理返回结果
        } else {
            // 处理请求失败的情况
        }
    }
})
添加拦截器
val client = OkHttpClient.Builder()
    .addInterceptor(Interceptor {
        val request = it.request()
            .newBuilder()
            .addHeader("Authorization", "Bearer " + token)
            .build()

        it.proceed(request)
    })
    .build()
上传文件
val client = OkHttpClient()

val file = File("/path/to/file")

val requestBody = MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", file.name, RequestBody.create(MediaType.parse("application/octet-stream"), file))
    .build()

val request = Request.Builder()
    .url("http://www.example.com/upload")
    .post(requestBody)
    .build()

val response = client.newCall(request).execute()

if (response.isSuccessful) {
    val body = response.body?.string()
    // 处理返回结果
} else {
    // 处理请求失败的情况
}

更多使用方式和 API 可以参考 OkHttp 的官方文档:https://square.github.io/okhttp/