【问题标题】:Java downloading file: "Connection timed out: connect"Java下载文件:“连接超时:连接”
【发布时间】:2017-06-08 15:17:58
【问题描述】:

当我使用以下代码下载文件 (35MB) 时。它给我的输出为:

连接超时:连接

以下是我用于文件下载过程的 java 代码。我该如何解决这个问题?

//download file
public void download(String url, File destination) throws IOException {
    URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destination);        
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}

public void parserAction() throws Exception {
    // InputStream is = new FileInputStream("en-parser-chunking.bin");
    File modelFile = new File("en-parser-chunking.bin");

    if (!modelFile.exists()) {
        System.out.println("Downloading model.");
        download("file://E:/Final Project/Softwares and tools/en-parser-chunking.bin", modelFile);

    }       
    ParserModel model = new ParserModel(modelFile);
    Parser parser = ParserFactory.create(model);
    Parse topParses[] = ParserTool.parseLine(line, parser, 1);
    for (Parse p : topParses) {
        //p.show();
        getNounPhrases(p);
    }
}

【问题讨论】:

  • 你想连接什么样的服务器?哪一行给了你错误?
  • 我正在将此文件从我的硬盘分区下载到我的 Web 应用程序。上传任务耗时太长,最后提示连接超时:connect。有什么办法可以阻止这个时间吗?还是加快下载任务?
  • 这是一个“连接超时”错误,所以你的问题不是速度,而是你实际上无法连接到服务器。我认为问题在于您使用的是“文件”协议,而它应该是 http,例如myserver/en-parser-chunking.bin".
  • 我不清楚如何使用 http 来完成这项任务。你能解释一下在这段代码中是怎么做的吗?
  • 您说您正在运行一个 Web 应用程序,因此应该只是将 URL 更改为您的 Web 服务器提供文档的位置,例如“http:...”等..

标签: java file url download timeout


【解决方案1】:

使用以下代码手动设置连接超时,看看哪个时间足以让文件成功上传:

            String url;            

         try{    
         HttpURLConnection Conn = (HttpURLConnection) new URL( url ).openConnection();

                                      Conn.setConnectTimeout(2000);
                                      Conn.setReadTimeout(2000);

             }
     catch (java.lang.ClassCastException|ConnectException|java.lang.IllegalArgumentException|java.net.MalformedURLException  ex) { }  //catch the possible exception.
     catch (SSLHandshakeException |SocketException | SocketTimeoutException | UnknownHostException ex)

顺便说一下,时间以毫秒为单位。

【讨论】:

  • 我将连接超时和读取超时都设置为 60000(60 秒)。大约 15 秒后仍然会抛出错误连接超时。我哪里做错了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2016-05-31
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多