Jetpack Compose 通过 OkHttp 发送 HTTP 请求的示例

下面是一个使用 Kotlin 和 Jetpack Compose 来演示通过 OkHttp 发送 HTTP 请求的示例。这个示例包括在 Jetpack Compose 中发送一个 GET 请求和一个 POST 请求,并显示结果。

添加okhttp依赖

首先,在你的 build.gradle.kts 文件中添加必要的依赖:

kotlin 复制代码
dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.10.0")
    //其他依赖
}

INTERNET 权限

你需要在 AndroidManifest.xml 文件中添加网络权限声明。请按照以下步骤操作:

  1. 打开 AndroidManifest.xml 文件。
  2. <manifest> 标签内添加 <uses-permission android:name="android.permission.INTERNET"/>

你的 AndroidManifest.xml 文件应该如下所示:

xml 复制代码
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <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.YourApp">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

添加这个权限声明后,再次运行你的应用程序,它应该能够正常进行网络请求。

主程序代码

kotlin 复制代码
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okio.IOException

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApp()
        }
    }
}

@Composable
fun MyApp() {
    var getResponse by remember { mutableStateOf("Loading...") }
    var postResponse by remember { mutableStateOf("Loading...") }

    LaunchedEffect(Unit) {
        getResponse = performGetRequest()
        postResponse = performPostRequest()
    }

    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = "GET Response:", style = MaterialTheme.typography.bodyLarge)
        Spacer(modifier = Modifier.height(8.dp))
        Text(text = getResponse)
        Spacer(modifier = Modifier.height(16.dp))
        Text(text = "POST Response:", style = MaterialTheme.typography.bodyLarge)
        Spacer(modifier = Modifier.height(8.dp))
        Text(text = postResponse)
    }
}

suspend fun performGetRequest(): String = withContext(Dispatchers.IO) {
    val client = OkHttpClient()
    val request = Request.Builder()
        .url("https://jsonplaceholder.typicode.com/posts/1")
        .build()

    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Unexpected code $response")
        response.body?.string() ?: "No response body"
    }
}

suspend fun performPostRequest(): String = withContext(Dispatchers.IO) {
    val client = OkHttpClient()
    val JSON = "application/json; charset=utf-8".toMediaType()
    val json = """{ "title": "foo", "body": "bar", "userId": 1 }"""
    val body = RequestBody.create(JSON, json)

    val request = Request.Builder()
        .url("https://jsonplaceholder.typicode.com/posts")
        .post(body)
        .build()

    client.newCall(request).execute().use { response ->
        if (!response.isSuccessful) throw IOException("Unexpected code $response")
        response.body?.string() ?: "No response body"
    }
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApp()
}

参考

某AI的生成

相关推荐
記億揺晃着的那天32 分钟前
HTTPS 页面内网直连 NAS:解决 Mixed Content 与公网带宽瓶颈
网络协议·http·https·nas
想学好C++的oMen3 小时前
socket编程TCP
linux·网络·网络协议·tcp/ip
GitLqr18 小时前
别再盲目复制了:彻底搞懂 CORS 的本质与那些“神坑”
安全·http·面试
IPdodo_1 天前
Codex 一直显示 Thinking 怎么办?区分任务运行、界面卡住与会话恢复
http·网络调试
2401_873479401 天前
SOC告警日志中IP归属不明怎么办?部署IP离线库三步提升响应效率
网络·网络协议·tcp/ip
Kina_C1 天前
Apache HTTP Server 安装、配置与高级功能详解
linux·http·apache
想学好C++的oMen1 天前
socket编程UDP
网络协议·udp
chexus1 天前
21. 深入 Nginx HTTP 缓存源码:CDN功能
nginx·http·缓存
GitLqr2 天前
玩转 WebSocket:从原理到 Flutter 实战
websocket·网络协议·flutter
微硬创新2 天前
耐达讯自动化 CC-Link IE 转 PROFINET网关在污水厂智能化升级实战
人工智能·物联网·网络协议·自动化·信息与通信