簡體   English   中英

使用Java在httpclient中下載文件?

[英]File download in httpclient using java?

我的代碼是

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,還是在防火牆后面?

在我的機器上重新編譯代碼,效果很好。 我可以從網上獲取文件。

檢查您的網絡瀏覽器是否可以為您下載文件(確保它不是網絡問題)

不過要注意的一件事是,在您的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*);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM