這個範例與之前的HttpURLConnection來實作get及post動作基本原理是一樣的,一個是使用java.io.BufferedReader來取得文字的html內容,而這個範例則是使用java.io.InputStream取得binary的檔案內容。
程式的流程大概是,先建立HttpConnection,給Connection標題Header、Referer、Cookie等內容,然後建立連線,跟伺服器request要求內容,再取得http的InputStrem,要取得伺服器response的內容,把內容讀取byte[],然後寫入檔案,如此就完成下載檔案的動作了。
程式碼如下:
package com.izero.http; import java.net.*; import java.net.Proxy.Type; import java.io.*; public class WebModuleDownload { private org.apache.log4j.Logger logger; private Proxy proxy; private String fileName; private String filePath; public WebModuleDownload() { logger = org.apache.log4j.Logger.getLogger(this.getClass()); // buff = new StringBuffer(); proxy = null; fileName = null; filePath = null; } // 如果要使用proxy,則使用此建構值 public WebModuleDownload(String proxyAddress, int proxyPort) { this(); proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); } // 下載後可取得檔案名稱,否則為null public String getFileName() { return fileName; } // 下載後可取得檔案路徑,否則為null public String getFilePath() { return filePath; } // 下載網址, // 使用cookie(可為null), // referer(可為null), // 存放檔案路徑(一定要有), // 存放檔案名稱(如為null則使用網址的檔名) public boolean doGet(String sURL, String cookie, String referer, String filePath, String fileName) { boolean doSuccess = true; BufferedReader in = null; try { URL url = new URL(sURL); HttpURLConnection URLConn = null; // 如有使用proxy,則openConnection時傳入proxy產數 if (proxy != null) URLConn = (HttpURLConnection) url.openConnection(proxy); else URLConn = (HttpURLConnection) url.openConnection(); // 要求的標頭header URLConn.setRequestProperty( "User-agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) " + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)"); URLConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); URLConn.setRequestProperty("Accept-Language", "zh-tw,en-us;q=0.7,en;q=0.3"); URLConn.setRequestProperty("Accept-Charse", "Big5,utf-8;q=0.7,*;q=0.7"); // 是否使用cookie if (cookie != null) URLConn.setRequestProperty("Cookie", cookie); // 是否使用referer if (referer != null) URLConn.setRequestProperty("Referer", referer); // URLConn.setDoInput(true); // URLConn.setDoOutput(true); // 建立連線 URLConn.connect(); // URLConn.getOutputStream().flush(); // 取得下載inputstream連線 java.io.BufferedInputStream rd = new java.io.BufferedInputStream( URLConn.getInputStream()); String saveFileName = fileName; // 檔名參數為null,則取下載網址的檔名為檔名 if (fileName == null) { int start = sURL.lastIndexOf("/") + 1; int end = sURL.lastIndexOf("?", start); if (end == -1) end = sURL.length(); // System.out.println(start+","+end); saveFileName = sURL.substring(start, end); } java.io.File f = new java.io.File(filePath); f = new java.io.File(f.getAbsolutePath()); if (!f.exists()) f.mkdirs(); f = new java.io.File(f.getAbsolutePath() + java.io.File.separator + saveFileName); this.fileName = saveFileName; // 取得路徑 this.filePath = f.getAbsolutePath(); java.io.BufferedOutputStream fos = new java.io.BufferedOutputStream( new java.io.FileOutputStream(f)); byte[] tmp = new byte[1024]; int len; // 讀取httpConection的input,寫出檔案的output while ((len = rd.read(tmp)) != -1) { // System.out.print(tmp); fos.write(tmp, 0, len); } fos.flush(); fos.close(); rd.close(); } catch (IOException e) { doSuccess = false; logger.info(e); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (java.io.IOException ex) { logger.info(ex); } in = null; } } return doSuccess; } public static void main(String args[]) throws IOException { WebModuleDownload web = new WebModuleDownload(); web.doGet("http://l.yimg.com/f/i/tw/news/p_logo/yptw.png", null, null, "d:/", null); /* * java.awt.image.BufferedImage image = javax.imageio.ImageIO .read(new * ByteArrayInputStream(web.getContent())); * javax.imageio.ImageIO.write(image, "JPEG", new * File("d:/HEX1PA35-A.JPG")); */ } }