Android/Kotlin:使用 URLConnection 发送数据时出现问题

Android/Kotlin: Problems when sending data with URLConnection

我正在尝试将数据从我的 android 应用程序的 activity 安全地发送到远程服务器上的 php 脚本。当我启动应用程序时,应用程序没有崩溃,也没有在控制台中提示任何错误消息。但是数据似乎没有发送到 php 脚本。

我试图通过在每行之间添加 Log.d(...) 命令来缩小可能发生错误的行的范围。当我 运行 应用程序处于调试模式时,每个 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()
    }
}

GameActivity.kt

<?php
    $param1 = $_POST["param1"];
    ...

file.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 的协议是“https”,因此将 URLConnection 转换为 HttpsURLConnection。然后,因为我们正在发送数据,所以将请求方法设置为“POST”。我们还将设置我们发送的数据的 content-type 以便我们的脚本知道会发生什么。所以这个 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()