为什么 HttpURLConnection 不发送 HTTP 请求

Why does HttpURLConnection not send the HTTP request

我想打开一个 URL 并向它提交以下参数,但它似乎只有在我将 BufferedReader 添加到我的代码时才有效。这是为什么?

Send.php 是一个脚本,它将向我的数据库添加一个带有时间的用户名。

以下代码不起作用(它不会向我的数据库提交任何数据):

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

但这段代码确实有效:

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

        final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        connection.disconnect();

据我所知。当您调用 connect() 函数时,它只会创建连接。

您至少需要调用 getInputStream()getResponseCode() 来提交连接,以便 url 指向的服务器能够处理请求。