使用java在httpclient中下载文件?
我的密码是使用java在httpclient中下载文件?,java,download,httpclient,Java,Download,Httpclient,我的密码是 import java.io.*; import java.net.*; public class DownloadHttp { public static void main(String a[]) { DownloadHttp d = new DownloadHttp(); String addr = "http://www.gmail.com"; String file = "D:/venkatesh/Software/downloa
import java.io.*;
import java.net.*;
public class DownloadHttp
{
public static void main(String a[])
{
DownloadHttp d = new DownloadHttp();
String addr = "http://www.gmail.com";
String file = "D:/venkatesh/Software/download1.html";
d.download(addr,file);
}
public void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
// Get the URL
URL url = new URL(address);
// Open an output stream to the destination file on our local filesystem
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
// Get the data
byte[] buffer = new byte[1024];
int numRead;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
}
// Done! Just clean up and get out
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
// Shouldn't happen, maybe add some logging here if you are not
// fooling around ;)
}
}
}
}
在这里,我想使用java下载使用httpClient的特定文件。
它产生:
"java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.
如何解决,请帮助我,提前谢谢。我认为这是一个网络问题。您是否尝试直接访问url,或者您是否在防火墙后面 在我的机器上重新编译您的代码,它运行得非常好。我能从网上获取文件 检查您的web浏览器是否可以为您下载文件(确保这不是网络问题) 但有一件事需要注意,在finally块中,您可能希望单独关闭流。因此,如果输入流出现任何问题,输出流仍将关闭
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ignored) {}
try {
if (out != null) {
out.close();
}
} catch (Exception ignored) {}
}
我认为您在连接到internet时使用的是代理 在代码中设置这些选项,然后重试
System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);
192.168.50.45的服务器似乎超时了。可能更多的是网络问题,而不是Java编码问题。更改URL后也会产生相同的错误。PS:您也不应该使用InputStream复制数据,因为它不可中断。改为使用通道(您可以从输入流创建通道:Channels.newChannel(inputStream)。关于如何将数据从一个通道复制到另一个通道,有大量的教程。