[HttpURLConnection如果未读取响应,则不会发送请求

问题描述 投票:0回答:1

我有一个简单的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,但是没有它,就不会发送我的请求。

android httpurlconnection
1个回答
0
投票
必须至少尝试读取响应(尽管,老实说,您为什么不检查响应以查看POST请求是否有效?)

请参阅此问题和答案:

Why does HttpURLConnection not send the HTTP request
© www.soinside.com 2019 - 2024. All rights reserved.