【问题标题】:HttpURLConnection does not send a request if the response is not read如果未读取响应,则 HttpURLConnection 不会发送请求
【发布时间】:2020-05-18 21:12:01
【问题描述】:

我有一个简单的 POST 请求:

        val url = URL(SEND_URL)

        val connection = url.openConnection() as HttpURLConnection

        connection.doOutput = true

        connection.addRequestProperty("Authorization", "...")
        connection.addRequestProperty("Content-Type", "application/json")

        val messageJson = Gson().toJson(message)

        val outputStream = OutputStreamWriter(connection.outputStream, "UTF-8")

        outputStream.write(messageJson)
        outputStream.flush()
        outputStream.close()

        connection.connect()

它不发送任何东西。

当我添加(而不是 connection.connect())时

        connection.responseCode
        connection.disconnect()

有效。

有人可以向我解释为什么会这样吗?我不需要阅读 response 或 responseCode,但没有它,我的请求不会被发送。

【问题讨论】:

  • connection.connect()。太晚了!您已经写入服务器。所以已经有联系了。现在您尝试再次连接?没有意义。写之前先联系。

标签: android httpurlconnection


【解决方案1】:

HttpURLConnection 就是这样工作的。在您尝试读取响应之前,它不会发送请求。您必须至少尝试阅读响应,即使您对响应不感兴趣(尽管,老实说,您为什么不检查响应以查看您的 POST 请求是否有效? )

查看这个问题和答案:

Why does HttpURLConnection not send the HTTP request

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多