方式一:使用okhttp3
okhttp官网
okhttp3 github地址
打开build.gradle.kts
文件加入依赖
dependencies {implementation("com.squareup.okhttp3:okhttp:4.9.0")
}
在IDEA的Gradle
面板点击reload
按钮便会自动下载jar
使用网络请求时需要把网络的权限打开,不然会提示java.lang.SecurityException: Permission denied (missing INTERNET permission?)
诸如此类的报错
在AndroidManifest.xml
文件的manifest
节点下添加如下代码以表示使用网络权限
<uses-permission android:name="android.permission.INTERNET"/>
为了方便使用可以对okhttp3进行封装一下
MainActivity.kt
代码如下
package com.demo.composestudyimport 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.TextAlignimport okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Responseimport java.io.IOExceptionclass 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线程
================================================
方式二:使用Retrofit2
Retrofit官网
Retrofit2快速入门
建议直接使用Retrofit2