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的生成

相关推荐
liann1197 小时前
3.2_红队攻击框架--MITRE ATT&CK‌
python·网络协议·安全·网络安全·系统安全·信息与通信
zjun10018 小时前
TCP专栏-1.TCP协议概念说明
网络·网络协议·tcp/ip
仍然.11 小时前
网络编程(二)---TCP字节流套接字编程
网络·网络协议·tcp/ip
Ether IC Verifier13 小时前
OSI网络七层协议详细介绍
服务器·网络·网络协议·计算机网络·php·dpu
环流_14 小时前
HTTP 协议的基本格式
java·网络协议·http
前端百草阁14 小时前
【吃透 Promise】从基础到面试高频(手写 + 输出题 + 原理)
okhttp·面试·职场和发展
AIwenIPgeolocation15 小时前
IP地址数据服务:赋能游戏行业体验优化与精细化运营
网络协议·tcp/ip·游戏
TechWayfarer16 小时前
2026年IP归属地查询平台选型指南:金融风控、异地登录、离线库全场景实测
网络·网络协议·tcp/ip
Rust研习社16 小时前
Rust + PostgreSQL 极简技术栈应用开发
开发语言·数据库·后端·http·postgresql·rust