为什么HttpURLConnection不发送HTTP请求

时间:2016-01-04 17:56:12

标签: 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();

但是这段代码确实有效:

        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 个答案:

答案 0 :(得分:3)

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

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