摘要:Java - Download Image with url
public void download_images(String download_path,String img_url) throws Exception
{
img_url =URIUtil.encodeQuery(img_url);
URL url = new URL(img_url);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(download_path);
fos.write(response);
fos.close();
}
這裡比較特別的會是URIUtil.encodeQuery(img_url);
原本使用URLEncoder.encode,
但空白,會變成+,無法連到正確位置,
空白必須轉成%20才可以。
使用URIUtil.encodeQuery,則會將空白直接轉%20,不必再自己將 +轉為encode