HttpURLConnection
是 Android 进行网络请求的一个轻量级 HTTP 客户端,适用于简单的 GET 和 POST 请求。以下是 HttpURLConnection
的基本使用方法。
使用步骤
- 创建 URL 对象
- 打开连接并配置请求
- 发送请求
- 读取响应
- 关闭连接
示例代码
1. GET 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import java.net.HttpURLConnection import java.net.URL
fun sendGetRequest(urlString: String): String? { var connection: HttpURLConnection? = null try { val url = URL(urlString) connection = url.openConnection() as HttpURLConnection connection.requestMethod = "GET" connection.connectTimeout = 5000 // 超时时间 connection.readTimeout = 5000 connection.doInput = true // 允许输入流
if (connection.responseCode == HttpURLConnection.HTTP_OK) { return connection.inputStream.bufferedReader().use { it.readText() } } } catch (e: Exception) { e.printStackTrace() } finally { connection?.disconnect() // 断开连接 } return null }
// 使用 val response = sendGetRequest("https://api.example.com/data") println(response)
|
2. POST 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import java.io.OutputStream import java.net.HttpURLConnection import java.net.URL
fun sendPostRequest(urlString: String, postData: String): String? { var connection: HttpURLConnection? = null try { val url = URL(urlString) connection = url.openConnection() as HttpURLConnection connection.requestMethod = "POST" connection.connectTimeout = 5000 connection.readTimeout = 5000 connection.doOutput = true // 允许输出流 connection.setRequestProperty("Content-Type", "application/json") // 发送 JSON 数据
// 发送数据 connection.outputStream.use { os: OutputStream -> os.write(postData.toByteArray()) os.flush() }
if (connection.responseCode == HttpURLConnection.HTTP_OK) { return connection.inputStream.bufferedReader().use { it.readText() } } } catch (e: Exception) { e.printStackTrace() } finally { connection?.disconnect() } return null }
// 使用 val jsonBody = """{"username":"test","password":"123456"}""" val postResponse = sendPostRequest("https://api.example.com/login", jsonBody) println(postResponse)
|
注意事项
网络请求必须在子线程执行
- 在 Android 9 及以上,主线程访问网络会抛出
NetworkOnMainThreadException
。
- 可以使用
Coroutine
或 Thread
处理。
使用 Coroutine
进行网络请求
1 2 3 4 5 6 7 8
| kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext
suspend fun fetchData(): String? { return withContext(Dispatchers.IO) { sendGetRequest("https://api.example.com/data") } }
|
使用 fetchData()
不能在主线程直接调用 fetchData()
,需要在协程中调用,例如:
1 2 3 4 5 6 7 8 9
| import kotlinx.coroutines.*
fun main() { GlobalScope.launch { val result = fetchData() println(result) } Thread.sleep(6000) // 等待协程执行(仅示例用,实际开发不推荐) }
|
权限
- 在
AndroidManifest.xml
中添加权限:
1
| <uses-permission android:name="android.permission.INTERNET"/>
|
超时设置
connectTimeout
和 readTimeout
防止请求长时间挂起。
替代方案
在 Android 现代开发中,建议使用 OkHttp
或 Retrofit
进行网络请求,HttpURLConnection
适用于轻量级请求或对库依赖要求较高的项目。
🔄 对比:HttpURLConnection vs OkHttp vs Retrofit
特性 |
HttpURLConnection |
OkHttp |
Retrofit |
原生支持 |
✅ |
❌(需导入库) |
❌(需依赖 OkHttp) |
简洁性 |
❌ |
✅ |
✅✅ |
请求配置 |
繁琐 |
简单 |
非常简单(注解) |
自动解析 JSON |
❌ |
❌(需手动) |
✅(配合 Gson/Moshi) |
拦截器支持 |
❌ |
✅ |
✅ |