2016-01-07 36 views
-2

我有下面的代碼來使用來自URL的httpclient下載文件。雖然該程序起作用,但每次運行時只下載3k。 我已經設置了幾個代理來克服企業網絡,並嘗試使用下面的代碼來自動從外部網站下載。在java中使用URL下載zip文件

該網站有一些其他文件(如視頻,音頻以及)。即使我嘗試與他們的大小是3K。我正在使用他們的REST接口來獲取文件。有什麼我需要改變我的代碼,使其仍然工作?

url = "https://samforloogin.com/video.zip"; 

URI uri = URI.create(url); 

DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); 
CloseableHttpClient httpclient = HttpClients.custom() 
       .setRoutePlanner(routePlanner) 
       .build(); 
HttpGet httpGet = new HttpGet(uri); 
httpGet.setHeader("Authorization", "Basic " + encoding); 
CloseableHttpResponse response = httpclient.execute(httpGet); 
java.io.InputStream is = response.getEntity().getContent(); 

String filePath = "C:\\Users\\smandodd\\AppData\\Local\\Temp\\8ee47df6c5a44c9d9c8ff3326d932819\\screenshots.flv"; 
FileOutputStream fos = new FileOutputStream(new File(filePath)); 
int inByte; 
while((inByte = is.read()) != -1) { 
    System.out.println("The number of bytes read are" + inByte); 
    fos.write(inByte); 
} 
is.close(); 
fos.close(); 
+1

你在'screenshots.flv'看到什麼短信?它可能會是一些文本指示HTTP錯誤。 –

+0

當你在調試器中運行時,你會看到什麼?你在調試器中運行它,不是嗎? –

+0

@MartinKonecny謝謝你的文件確實有錯誤信息... – user2189668

回答

0

您可以使用下面的代碼來下載一般文件:

URL website = new URL("https://samforloogin.com/video.zip"); 
ReadableByteChannel rbc = Channels.newChannel(website.openStream()); 
FileOutputStream fos = new FileOutputStream(filePath); 
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);