在java中使用URL下载zip文件

时间:2016-01-07 16:47:52

标签: java rest httpclient

我有以下代码使用URL中的httpclient下载文件。虽然该程序有效但每次运行时它只下载3k。 我已经设置了几个代理来克服企业网络,我正在尝试以下代码来自动从外部网站下载。

该网站还有一些其他文件(如视频,音频)。即使我尝试使用它们,尺寸也是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 个答案:

答案 0 :(得分: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);