安卓/ Kotlin : Problems when sending data with URLConnection

标签 android kotlin httpsurlconnection

我正在尝试将数据从我的 android 应用程序的 Activity 安全地发送到远程服务器上的 php 脚本。当我启动应用程序时,应用程序没有崩溃,我也没有在控制台中提示任何错误消息。但是数据似乎没有发送到 php 脚本。
我试图通过在每行之间添加 Log.d(...) 命令来缩小可能发生错误的行。当我在 Debug模式下运行应用程序时,每个 Log.d(...) 都会打印到控制台,所以我预计 php 脚本不正确。然而,进一步的调查显示数据没有到达 php 脚本,因为 $score = $_POST["score"] 不包含预期值。另外,如果我任意更改请求的 url 并再次启动应用程序,也不会出现错误消息。所以我希望错误位于 MyActivity.kt 文件中的 url.openConnection() 和 urlConnection.connect() 之间。
问题
为什么代码没有将数据发送到脚本,我该如何解决?

class MyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        this.configureNetworkRunnable()
    }
   
    private fun configureNetworkRunnable() {
        Thread( Runnable {
            uploadData()
        }).start()
    }

    private fun uploadData() {
        val charset = "UTF-8"
        val parameter = URLEncoder.encode("param1", charset) + "=" + URLEncoder.encode("20", charset)

        val url = URL("https://www.myurl.com/path/file.php")
        val urlConnection = url.openConnection()
        urlConnection.setDoOutput(true)

        val outputStream: OutputStream = urlConnection.getOutputStream()
        outputStream.write(parameter.toByteArray(Charsets.UTF_8))
        urlConnection.connect()
    }
}
游戏 Activity .kt
<?php
    $param1 = $_POST["param1"];
    ...
文件.php
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/OpenGLRenderer: makeCurrent EglSurface : 0x7cf3783000 -> 0x7cf3783b00
D/ViewRootImpl@1b125bd[GameActivity]: MSG_RESIZED: frame=(112,0,2280,1080) ci=(0,0,0,0) vi=(0,0,0,0) or=2
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/TcpOptimizer: TcpOptimizer-ON
D/libmdf: libmdf v2.9.0.0 On 64bit PLATFORM
D/OpenGLRenderer: destroyEglSurface : 0x7cf3783000
I/mali_egl: eglDestroySurface() in
I/mali_winsys: delete_surface() [2168x1080] return
I/mali_egl: eglDestroySurface() out
W/libEGL: EGLNativeWindowType 0x7d82347810 disconnect failed
D/OpenGLRenderer: ~ReliableSurface : 0x7d82347800
D/ViewRootImpl@fc1415c[MainActivity]: Relayout returned: old=(112,0,2280,1080) new=(112,0,2280,1080) req=(2168,1080)8 dur=10 res=0x5 s={false 0} ch=true
D/ViewRootImpl@fc1415c[MainActivity]: stopped(true) old=false
V/ViewRootImpl@fc1415c[MainActivity]: updateAppliedLetterboxDirection, direction=0, Caller=android.view.ViewRootImpl.handleDispatchLetterboxDirectionChanged:8044
安慰
先感谢您。

最佳答案

由于该 URL 的协议(protocol)是“https”,因此将该 URLConnection 转换为 HttpsURLConnection。然后,由于我们正在发送数据,请将请求方法设置为“POST”。我们还将设置我们发送的数据的内容类型,以便我们的脚本知道会发生什么。所以这个 HttpsURLConnection 的构造应该是这样的:

val urlConnection = url.openConnection() as HttpsURLConnection
urlConnection.apply {
  requestMethod = "POST"
  doOutput = true
  setRequestProperty("Content-Type", "application/octet-stream")
}
发送数据后,您似乎也没有正确关闭流。尝试:
urlConnection.outputStream.use { stream ->
  stream.write("20".toByteArray(Charsets.UTF_8))
}
这会将字节写入您的流并为您处理关闭它,无论是否异常。
最后,您必须完整阅读 inputStream,因此请尝试:
urlConnection.inputStream.bufferedReader().use {
  it.readText()
}
如果您仍然遇到问题,请打印以记录您的 urlConnection.responseCode以及可选的 it.readText()为了我。

关于安卓/ Kotlin : Problems when sending data with URLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63292904/

相关文章:

java - HttpsURLConnection 的 SSLSocket

java - 通过 post 方法发出带有参数的 HttpsURLConnection 请求

android - 一个屏幕上的两个 RecyclerView

python - 加速器数据应该具有什么样的结构来进行模型预测?

android - 在 SDK 中使用新的 Android 广告商 ID

可变列表的 java 到 kotlin 语言翻译问题

android - 在Firebase登录上实现Smart Lock密码

Android - 崩溃后文件为空

android - 升级androidx时资源 'attr/visibility'的值重复

java - 超时没有限制吗? - HttpsURL连接