为什么 HttpURLConnection 不发送 HTTP 请求

Kev*_*n S 3 java http httpurlconnection

我想打开一个 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();
Run Code Online (Sandbox Code Playgroud)

但这段代码确实有效:

        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();
Run Code Online (Sandbox Code Playgroud)

kuc*_*ang 7

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

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

  • 查看 JDK 源代码证实了这一点。在您调用 getInputStream() 之前,连接不会发送请求 (3认同)