本工具類支持url的list集合,具體實現如下所示:
public static void download(ArrayList<String> listUrl,
String downloadPath) {
for (String url : listUrl) {
try {
getImageFromNetByUrl(url,downloadPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void getImageFromNetByUrl(String strUrl,String path) throws Exception {
String imageName = strUrl.substring(strUrl.lastIndexOf("/") + 1,
strUrl.length());
_FakeX509TrustManager.allowAllSSL();
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();// 通過輸入流獲取圖片數據
byte[] btImg = readInputStream(inStream);// 得到圖片的二進制數據
inStream.close();
conn.disconnect();
try {
File file = new File(path+imageName);
DirectoryUtil.createFile(path+imageName);
FileOutputStream fops = new FileOutputStream(file);
fops.write(btImg);
fops.flush();
fops.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
本方法支持自定義路徑:
調用事例:
//urlList 圖片的網絡地址的集合 ArrayList<String> urlList = new ArrayList<String>(); pictureFileUtil.download(urlList,"c:/demo/..下載的路徑");
親測好使。。。
