打开build.gradle.kts
文件加入依赖
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.9.0")
}
在IDEA的Gradle
面板点击reload
按钮便会自动下载jar
MainActivity.kt
代码如下
package com.demo.composestudy
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
showUI()
}
}
}
@Composable
fun showUI(){
var resultstring by remember { mutableStateOf("") }
Column(){
Button(
onClick = {
var url = "https://www.baidu.com";
val client = OkHttpClient();
// 创建一个Request对象
var request: Request = Request.Builder()
.url(url)
.build();
//发起call请求
val call: Call = client.newCall(request)
//异步请求
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d(TAG, "onFailure IOException:{$e}");
}
override fun onResponse(call: Call, response: Response) {
//接收返回响应
val result = response.body?.string()?:"";
resultstring = result;
Log.d(TAG, "result:{$result}");
}
});
}){
Text("点击进行请求")
}
Text(
"$resultstring",
Modifier.fillMaxWidth(),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.titleMedium
)
}
}
这里需要使用异步请求,使用同步请求会阻塞Android的UI线程