Search code examples
androidhttpurlconnection

HttpURLConnection does not send a request if the response is not read


I have a simple POST request:

        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()

It does not send anything.

When I add (instead of connection.connect())

        connection.responseCode
        connection.disconnect()

It works.

Could someone please explain to me why is it so? I do not need to read the response or responseCode but without it, my request is not being sent.


Solution

  • That's the way HttpURLConnection works. It doesn't send the request until you attempt to read the response. You must at least attempt to read the response, even if you aren't interested in the response (although, to be honest, why aren't you checking the response to see if your POST request worked?)

    See this question and answer:

    Why does HttpURLConnection not send the HTTP request