简体   繁体   English

使用Java在httpclient中下载文件?

[英]File download in httpclient using java?

My code is, 我的代码是

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 ;)
    }
  }
 }
 }

Here I wants download specific file using httpClient using java. 在这里,我想使用java使用httpClient下载特定文件。 It produces: 它产生:

"java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)" as error.

How to resolve it, help me, thanks in advance. 如何解决,请帮助我,谢谢。

I believe it is a network problem. 我相信这是网络问题。 Have you tried to access the url directly or are you behind a firewall? 您是否尝试过直接访问URL,还是在防火墙后面?

Recompiled your code on my machine, it works perfectly well. 在我的机器上重新编译代码,效果很好。 I'm able to fetch files from the web. 我可以从网上获取文件。

Check if your web-browser can download the file for you (make sure it's not a network problem) 检查您的网络浏览器是否可以为您下载文件(确保它不是网络问题)

One thing to notice though, in your finally block you might want to close the streams separately. 不过要注意的一件事是,在您的finally块中,您可能想单独关闭流。 So if anything goes wrong with the input stream, the output stream will still be closed. 因此,如果输入流出现任何问题,则输出流仍将关闭。

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

I think you are using a proxy when connecting to internet. 我认为您在连接到Internet时正在使用代理。

Set these in the code and then retry. 在代码中设置这些,然后重试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM