您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
javase实现网络url文件下载(解决小文件下载问题)
发布时间:2017-09-22 20:08:26编辑:雪饮阅读()
上一版最后发现在比较小的文件下载时,虽然也能下载但是下载后的文件有异常。并且好像不支持for循环的方式。据说在大文件下载时也有不稳定的情况。
该版本使用httpclient4.1解决了该问题。
所需附件打包下载:
如下示例中使用了循环下载,也可以单个下载
package test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpUtil {
public static void main(String[] args) throws Exception {
String[] strArr=new String[2];
strArr[0]="http://www.xynes.cn/uploadfile/2016/0125/20160125030254519.jpg";
strArr[1]="http://www.xynes.cn/uploadfile/2016/0125/20160125025921399.jpg";
int i=0;
for(String s : strArr){
down(s,i+".jpg");
i++;
}
}
public static void down(String url,String filename) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == 200) {
File xml = new File("d:/sitemap/"+filename);
FileOutputStream outputStream = new FileOutputStream(xml);
InputStream inputStream = httpResponse.getEntity().getContent();
byte buff[] = new byte[4096];
int counts = 0;
while ((counts = inputStream.read(buff)) != -1) {
System.out.println(".......");
outputStream.write(buff, 0, counts);
}
outputStream.flush();
outputStream.close();
}
httpClient.getConnectionManager().shutdown();
System.out.println("success: ");
}
}
关键字词:javase,网络,url,文件,下载