问题描述: 在Android/Kotlin开发中,使用URLConnection发送数据时遇到的问题是如何正确使用URLConnection发送数据。
解决方法: 以下是一个使用URLConnection发送数据的示例代码:
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
fun sendData(urlString: String, data: String): String {
var connection: HttpURLConnection? = null
var response = ""
try {
val url = URL(urlString)
connection = url.openConnection() as HttpURLConnection
connection.doOutput = true
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/json")
connection.setRequestProperty("Accept", "application/json")
val dataBytes = data.toByteArray(StandardCharsets.UTF_8)
connection.setRequestProperty("Content-Length", dataBytes.size.toString())
val outputStream = BufferedOutputStream(connection.outputStream)
outputStream.write(dataBytes)
outputStream.flush()
outputStream.close()
val inputStream = BufferedReader(InputStreamReader(connection.inputStream))
val stringBuilder = StringBuilder()
var line: String?
while (inputStream.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
inputStream.close()
response = stringBuilder.toString()
} catch (e: Exception) {
e.printStackTrace()
} finally {
connection?.disconnect()
}
return response
}
在上面的示例中,我们定义了一个sendData函数,该函数接受一个URL字符串和要发送的数据。函数使用URLConnection来发送POST请求,并将数据作为JSON字符串进行发送。
要使用该函数发送数据,只需调用sendData函数并传递正确的URL和要发送的数据即可,例如:
val url = "https://example.com/api"
val data = "{\"key\": \"value\"}"
val response = sendData(url, data)
println(response)
请确保在调用sendData函数之前,您已经在Android清单文件中添加了网络权限:
这样就可以使用URLConnection在Android/Kotlin中发送数据了。