Android/Kotlin:使用URLConnection发送数据时遇到的问题
创始人
2024-08-20 07:00:47
0

问题描述: 在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中发送数据了。

相关内容

热门资讯

推荐一款(cloudpoker... 推荐一款(cloudpoker云扑克辅助)软件透明挂(辅助挂)果真是真的有挂(有挂详情)-哔哩哔哩;...
六分钟了解(德扑之星开房间教程... 六分钟了解(德扑之星开房间教程)软件透明挂(辅助挂)其实是真的有挂(有挂教程)-哔哩哔哩是由北京得德...
玩家必用(扑克之城那假)透视辅... 1、玩家必用(扑克之城那假)透视辅助(透视)果真是真的有挂(有挂规律)-哔哩哔哩(UU poker、...
玩家亲测(gg扑克辅助)透视辅... 《gg扑克辅助软件透明挂》是一款多人竞技的gg扑克辅助辅助透视游戏,你将微扑克对手来到同一个战场,为...
每日必看教程(德扑之星用刷数据... 每日必看教程(德扑之星用刷数据)软件透明挂(透视)果真真的有挂(有挂攻略)-哔哩哔哩是一款可以让一直...
一分钟了解(德州alphax辅... 一分钟了解(德州alphax辅助)软件透明挂(透视)竟然是真的有挂(有挂透明)-哔哩哔哩;科技安装教...
透视能赢(德扑之星有规律)透视... 透视能赢(德扑之星有规律)透视辅助(透视)竟然是真的有挂(有挂规律)-哔哩哔哩;(需添加指定薇757...
四分钟了解(哈糖大菠萝平台正规... WePoker透视辅助工具核心要点解析‌,四分钟了解(哈糖大菠萝平台正规)辅助透视(辅助挂)原来是真...
实测分享(拱趴大菠萝切牌规律)... 实测分享(拱趴大菠萝切牌规律)辅助透视(辅助挂)其实真的有挂(有挂了解)-哔哩哔哩;揭秘教程安装方法...
5分钟了解(fishpoker... 5分钟了解(fishpoker正规)透视辅助(透视)其实真的有挂(有挂了解)-哔哩哔哩1、许多玩家不...