为什么HttpURLConnection没有发送HTTP请求

3
我希望打开一个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();

1
如果需要使用HTTP进行编程,请考虑使用一些第三方库。Apache HttpClient是一个非常不错的选择。使用Java内置的网络功能来处理网络请求并不是很方便。 - coolguy
1个回答

7
据我所知,当您调用connect()函数时,它只会创建连接。
您需要至少调用getInputStream()getResponseCode()来提交连接,以便指向的服务器能够处理请求。

3
查看 JDK 源代码可以确认:直到调用 getInputStream() 方法之前,连接并不会发送请求。 - Monz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接