【问题标题】:Why does HttpURLConnection not send the HTTP request为什么 HttpURLConnection 不发送 HTTP 请求
【发布时间】:2016-01-04 17:56:12
【问题描述】:

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

【问题讨论】:

  • 如果您需要使用 HTTP,请考虑使用一些第三方库。 Apache HttpClient 很不错。使用内置 Java 工具的网络不是很舒服

标签: java http httpurlconnection


【解决方案1】:

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

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

【讨论】:

  • 查看JDK源码确认。在您调用 getInputStream() 之前,连接不会发送请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 2020-07-05
  • 2018-02-19
  • 2013-09-18
相关资源
最近更新 更多