【问题标题】:How to solve java.net.ConnectException: Connection Timed out [duplicate]如何解决 java.net.ConnectException:连接超时 [重复]
【发布时间】:2019-06-25 21:13:45
【问题描述】:

我正在尝试使用以下代码连接 Google.com,但得到了

java.net.ConnectException:连接超时
。 请帮忙!
private static String getUrlContents(String theUrl) {

    StringBuilder content = new StringBuilder();

    // many of these calls can throw exceptions, so i've just
    // wrapped them all in one try/catch statement.
    try {
        // create a url object
        URL url = new URL(theUrl);

        // create a urlconnection object
        URLConnection urlConnection = url.openConnection();

        // wrap the urlconnection in a bufferedreader
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        String line;

        // read from the urlconnection via the bufferedreader
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}

【问题讨论】:

  • 网址是http://www.google.com?
  • 你的电脑和互联网之间有防火墙吗?

标签: java exception httpurlconnection


【解决方案1】:

所以,您不是在问该怎么做如何在 java 中从 URL 读取内容? Read url to string in few lines of java code.

描述了一个问题,您希望得到分析甚至解决:

获取java.net.ConnectException: Connection timed out

following answer提问Connection timed out. Why?

你应该看的东西:

您的问题很可能与防火墙有关。我的第一个猜测是您没有设置正确的环境变量或 Java 系统属性来告诉 JVM 使用本地代理服务器来处理传出的 HTTP / HTTPS 请求

从 URL 读取内容的另一种方法可能是免费的开源 JSoup 库。看看如何在您的情况下使用它:http://jsoup.org/cookbook/input/load-document-from-url

使用 JSoup,您甚至可以优雅地解析返回的 HTML 文档。

【讨论】:

  • 他不需要知道如何使用超时。他已经超时了。他需要知道如何得到一个。而且您不能延长默认连接超时。你只能减少它。而且您的引文都没有说明任何不同。
  • @user207421 修改了我的答案以解决指定的ConnectException 并建议重命名此问题的标题。我针对这个异常研究了stackoverflow,发现了很多java网络主题,你总是批评答案,但自己没有提供一些答案。如果您自己提供(更好的)答案,您的见解也可能很有价值。
【解决方案2】:

我刚刚尝试了您的代码,它运行良好。

似乎是网络问题,可能是您没有 Internet 访问权限,或者防火墙正在停止连接。假设您在 UNIX 系统中尝试:

  1. ping www.google.com -C 1 如果您没有得到答复并且您有正常的访问连接(即从您的浏览器),则可能是防火墙问题。

  2. traceroute www.google.com 检查 google 的服务器通常应为一或两的跃点数。

如果您在 CentOS 上,您应该尝试停止防火墙进行测试,因为它非常严格: sudo systemctl stop firewalld 请记住重新启动它并添加执行请求所需的规则。

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 2012-05-31
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多