【问题标题】:Getting Connection timed out: connect连接超时:连接
【发布时间】:2015-05-27 09:25:14
【问题描述】:

我收到连接超时:java 代码中的连接异常,请参见下文。 我已经在谷歌搜索但没有得到太多帮助,你可以在你的机器上运行这个代码,我在下面给出它的完整代码。 代码-

public class download {
    // final static int size=1024;

    public static void downloadValuationPDFReport() {
        OutputStream outStream = null;
        URLConnection uCon = null;
        InputStream is = null;
        String fAddress = null;
        URL Url = null;
        String localFileName = "abc.zip";
        String destinationDir = "H:\\";//"C:\\Users\\501301605\\Downloads";
        try {
            fAddress = "http://www.novell.com/coolsolutions/tools/downloads/ntradping.zip";
            byte[] buf;
            int byteRead = 0;
            Url = new URL(fAddress);
            outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName));
            uCon = Url.openConnection();
            is = uCon.getInputStream();
            buf = new byte[1024];
            while ((byteRead = is.read(buf)) != -1) {
                outStream.write(buf, 0, byteRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

【问题讨论】:

  • 你可以尝试设置一些连接超时:uCon .setConnectTimeout(VALUE); uCon.setReadTimeout(VALUE);
  • @SaqibRezwan 感谢您的评论,但遇到同样的问题
  • 适合我。防火墙问题?你能直接下载文件吗(从浏览器)?
  • 您是否使用了代理或防火墙?
  • 你为什么认为 Java 会自动知道你的浏览器代理设置?

标签: java jakarta-ee


【解决方案1】:

很可能您所在的网络不允许您直接连接到任何端口 80;尝试:

telnet www.novell.com 80

看看你是否得到答案;这也可能会导致超时。

您很可能需要使用代理(例如,请参阅here)。此外,您的代码使许多资源悬而未决,并且您使用已过时的File

下面是如何用现代代码做到这一点:

final Path dstfile = Paths.get("h:", "abc.zip");

// ...

try (
    final InputStream in = url.openStream();
) {
    Files.copy(in, dstfile, StandardOpenOption.CREATE_NEW);
}

【讨论】:

  • 是的,无法连接到主机。那么如何使用代理服务器?您能帮忙解决这个问题吗?
  • 编辑了答案以添加链接;也尝试搜索一下。
猜你喜欢
  • 2022-01-21
  • 2013-09-03
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 2014-04-07
  • 2014-03-01
相关资源
最近更新 更多