2017/10/11 更新,寫了新的一篇,包含了HTTPS,User-Agent,Content-Type等更詳細的
細節
以Java 由Url下載圖片
package readFileFromUrlTest; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; public class ReadFileFromUrlTest { public static void main(String[] args) { ReadFileFromUrlTest readFileFromUrlTest = new ReadFileFromUrlTest(); String url = "https://www.vermontteddybear.com/media/wysiwyg/VTB-CMS-Content/featuredcat-KBKF36004-20170119.jpg"; String filePath = "D:\\xxx.jpg"; try { readFileFromUrlTest.readFileFromUrl(new URL(url), new File(filePath)); } catch (IOException ex) { Logger.getLogger(ReadFileFromUrlTest.class.getName()).log(Level.SEVERE, null, ex); } } public void readFileFromUrl(URL url, File file) throws IOException { BufferedInputStream bufferedInputStream = null; FileOutputStream fileOutputStream = null; try { bufferedInputStream = new BufferedInputStream(url.openStream()); fileOutputStream = new FileOutputStream(file); int data; //從串流讀取資料寫到檔案中 while ((data = bufferedInputStream.read()) != -1) { fileOutputStream.write(data); } } catch (IOException ex) { throw ex; } finally { //關閉串流 try { if (file != null) { fileOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } catch (IOException ex) { throw ex; } } } }
參考資料:
沒有留言 :
張貼留言