jetpackcompose 中处理 OKhttp
时间: 2023-12-23 15:04:16 浏览: 103
在 Jetpack Compose 中使用 OKhttp 需要遵循以下步骤:
1. 添加依赖:在 app 模块的 build.gradle 文件中添加以下依赖:
```
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
```
2. 创建 OkHttp 实例:在 Composable 函数中创建 OkHttp 实例。
```
val client = OkHttpClient()
```
3. 创建 Request 对象:创建一个 Request 对象,设置 URL 和请求方式等属性。
```
val request = Request.Builder()
.url(url)
.build()
```
4. 发送请求:使用 OkHttp 的 `newCall()` 方法发送请求。
```
val call = client.newCall(request)
val response = call.execute()
```
5. 处理响应:获取响应数据,并在 Composable 函数中使用。
```
val body = response.body?.string()
Text(text = body)
```
完整示例代码:
```
@Composable
fun OkHttpExample() {
val url = "https://jsonplaceholder.typicode.com/todos/1"
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
val call = client.newCall(request)
val response = call.execute()
val body = response.body?.string()
Text(text = body ?: "No response")
}
```