url openstream中的连接太多

时间:2013-08-16 12:15:21

标签: java file url connection

我首先在这里尝试检查,如果URL上的文件存在,然后是否存在下载它。但是它让我失望了

线程“main”中的异常sun.net.ftp.FtpProtocolException:欢迎消息:421来自此IP的连接数太多(2)

如果我知道,我总是关闭连接,但无论如何它会崩溃

private boolean exists(String URLName) throws MalformedURLException, IOException {
    boolean result = false;
        URL url = new URL(URLName);
        input = url.openStream();
        input.close();
        result = true;  
    return result;
}

private void downloadTheFile(String path, String name) throws MalformedURLException, IOException {
    input.close();
    input = new URL(path).openStream();
    try {
    OutputStream out = new FileOutputStream(name + ".pdf");
        byte buf[] = new byte[4096];
        for (int n = input.read(buf); n > 0; n = input.read(buf)) {
            out.write(buf, 0, n);
        }
    } finally {
        out.close();
        input.close();
    }
}

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

服务器发现您创建了太多不同的连接,并立即启动。不要为每个文件创建单独的连接。

虽然我无法确定您是如何调用下载功能的,但请考虑通过Apache Commons::net使用持久连接。

答案 1 :(得分:0)

摆脱exists()方法。如果文件不存在,下载方法将失败。仅这一点就可以将你的连接减少一半。