我得到连接超时:在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 :(得分: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);
}