使用java在httpclient中下载文件?

时间:2011-01-21 09:40:29

标签: 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/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.

如何解决它,帮助我,提前谢谢。

3 个答案:

答案 0 :(得分:1)

我认为这是一个网络问题。您是否尝试直接访问该URL或是否在防火墙后面?

答案 1 :(得分:1)

在我的机器上重新编译代码,它运行得非常好。我能够从网络上获取文件。

检查您的网络浏览器是否可以为您下载文件(确保它不是网络问题)

有一件事需要注意,在您的finally块中,您可能希望单独关闭流。因此,如果输入流出现任何问题,输出流仍将关闭。

finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception ignored) {}
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception ignored) {}
    }

答案 2 :(得分:0)

我认为您在连接互联网时使用代理。

在代码中设置这些,然后重试。

System.setProperty("http.proxyHost", *Proxy-IP*);
System.setProperty("http.proxyPort", *Proxy-Port*);