下面是一个使用 Kotlin 和 Jetpack Compose 来演示通过 OkHttp 发送 HTTP 请求的示例。这个示例包括在 Jetpack Compose 中发送一个 GET 请求和一个 POST 请求,并显示结果。
添加okhttp依赖
首先,在你的 build.gradle.kts
文件中添加必要的依赖:
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.10.0")
//其他依赖
}
INTERNET 权限
你需要在 AndroidManifest.xml
文件中添加网络权限声明。请按照以下步骤操作:
- 打开
AndroidManifest.xml
文件。 - 在
<manifest>
标签内添加<uses-permission android:name="android.permission.INTERNET"/>
。
你的 AndroidManifest.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>
添加这个权限声明后,再次运行你的应用程序,它应该能够正常进行网络请求。
主程序代码
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的生成