【问题标题】:URL connection HTTP POST connection refusedURL 连接 HTTP POST 连接被拒绝
【发布时间】:2013-01-20 23:32:25
【问题描述】:

我正在使用 Java 7 开发 Java 桌面应用程序。对于我的应用程序,我想通过 POST 将数据发送到服务器(使用 HTTP)。该服务器正在本地主机上的本地计算机上运行。 但是,如果我尝试连接到服务器,则会返回连接重置 (SocketTimeoutException)。我无法连接,我也尝试连接到像http://www.google.de 这样的网页,但它也失败了。 var 正文包含正确格式的 POST 数据。 (我也尝试过连接禁用的防火墙) 我的代码:

body=body.substring(0,body.length()-2);
HttpURLConnection connection = null;
try {
    if (revision){ //Connect to the revision server
        this.urlRevision = new URL(this.settingsRevision.getAddress());
        connection = (HttpURLConnection) urlRevision.openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(body.length()));
        connection.connect();
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(body);
        writer.flush();

        this.returnedData = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        for(String line; (line = returnedData.readLine()) != null;){
            System.out.println(line);
        }
        writer.close();
        this.returnedData.close();
    }
} catch (Exception e) {
        this.exception=e;
}

【问题讨论】:

  • 请在浏览器中尝试localhost。其他一些服务器可能正在运行。你的服务器是什么?
  • Localhost 在我的浏览器中运行,我正在访问我的本地 xampp 服务器(apache 服务器)的起始页
  • 使用:System.setProperty("java.net.preferIPv4Stack" , "true");

标签: java http url connection


【解决方案1】:

您应该尝试像这样关闭连接:

} finally {
    if(connection != null) {
      connection.disconnect(); 
    }
}

【讨论】:

  • 我添加了这个,但是SocketTimeoutException又出现了。
  • 你可以在没有 POST 任何数据的情况下连接吗?
【解决方案2】:

我已经将它添加到 cmets 中了:

System.setProperty("java.net.preferIPv4Stack" , "true");

原因:Java 在我的计算机上使用 IPv6 功能,但 IPv4 用于 Internet 连接(在我的计算机上并由我的提供商 (T-Online))。

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2015-04-07
    • 2018-03-10
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    相关资源
    最近更新 更多