2015-05-27 103 views
1

我收到連接超時:在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(); 
      } 
     } 
    } 
} 
+0

你可以嘗試設置一些連接超時: UCON .setConnectTimeout(VALUE); uCon.setReadTimeout(VALUE); –

+0

@SaqibRezwan感謝您的評論,但得到同樣的問題 – RSingh

+3

適合我的作品。防火牆問題?你能直接從瀏覽器下載文件嗎? – agad

回答

2

這很可能是你在哪裏,你都不能直接連接到任何一個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); 
} 
+0

是得到無法連接到主機。然後如何使用代理seetings?你可以幫助這個plzz? – RSingh

+0

編輯答案爲其添加鏈接;嘗試和搜索。 – fge

+0

非常感謝你,它的工作。 – RSingh