HttpClient实现HTTP文件通用下载类

Java代码  
  1 import java.io.File;  
  2 import java.io.FileOutputStream;  
  3 import java.io.InputStream;  
  4   
  5 import org.apache.http.Header;  
  6 import org.apache.http.HeaderElement;  
  7 import org.apache.http.HttpEntity;  
  8 import org.apache.http.HttpResponse;  
  9 import org.apache.http.NameValuePair;  
 10 import org.apache.http.client.HttpClient;  
 11 import org.apache.http.client.methods.HttpGet;  
 12 import org.apache.http.impl.client.DefaultHttpClient;  
 13   
 14 /** 
 15  * 说明 
 16  * 利用httpclient下载文件 
 17  * maven依赖 
 18  * <dependency> 
 19 *           <groupId>org.apache.httpcomponents</groupId> 
 20 *           <artifactId>httpclient</artifactId> 
 21 *           <version>4.0.1</version> 
 22 *       </dependency> 
 23 *  可下载http文件、图片、压缩文件 
 24 *  bug:获取response header中Content-Disposition中filename中文乱码问题 
 25  * @author tanjundong 
 26  * 
 27  */  
 28 public class HttpDownload {  
 29   
 30     public static final int cache = 10 * 1024;  
 31     public static final boolean isWindows;  
 32     public static final String splash;  
 33     public static final String root;  
 34     static {  
 35         if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {  
 36             isWindows = true;  
 37             splash = "\\";  
 38             root="D:";  
 39         } else {  
 40             isWindows = false;  
 41             splash = "/";  
 42             root="/search";  
 43         }  
 44     }  
 45       
 46     /** 
 47      * 根据url下载文件,文件名从response header头中获取 
 48      * @param url 
 49      * @return 
 50      */  
 51     public static String download(String url) {  
 52         return download(url, null);  
 53     }  
 54   
 55     /** 
 56      * 根据url下载文件,保存到filepath中 
 57      * @param url 
 58      * @param filepath 
 59      * @return 
 60      */  
 61     public static String download(String url, String filepath) {  
 62         try {  
 63             HttpClient client = new DefaultHttpClient();  
 64             HttpGet httpget = new HttpGet(url);  
 65             HttpResponse response = client.execute(httpget);  
 66   
 67             HttpEntity entity = response.getEntity();  
 68             InputStream is = entity.getContent();  
 69             if (filepath == null)  
 70                 filepath = getFilePath(response);  
 71             File file = new File(filepath);  
 72             file.getParentFile().mkdirs();  
 73             FileOutputStream fileout = new FileOutputStream(file);  
 74             /** 
 75              * 根据实际运行效果 设置缓冲区大小 
 76              */  
 77             byte[] buffer=new byte[cache];  
 78             int ch = 0;  
 79             while ((ch = is.read(buffer)) != -1) {  
 80                 fileout.write(buffer,0,ch);  
 81             }  
 82             is.close();  
 83             fileout.flush();  
 84             fileout.close();  
 85   
 86         } catch (Exception e) {  
 87             e.printStackTrace();  
 88         }  
 89         return null;  
 90     }  
 91     /** 
 92      * 获取response要下载的文件的默认路径 
 93      * @param response 
 94      * @return 
 95      */  
 96     public static String getFilePath(HttpResponse response) {  
 97         String filepath = root + splash;  
 98         String filename = getFileName(response);  
 99   
100         if (filename != null) {  
101             filepath += filename;  
102         } else {  
103             filepath += getRandomFileName();  
104         }  
105         return filepath;  
106     }  
107     /** 
108      * 获取response header中Content-Disposition中的filename值 
109      * @param response 
110      * @return 
111      */  
112     public static String getFileName(HttpResponse response) {  
113         Header contentHeader = response.getFirstHeader("Content-Disposition");  
114         String filename = null;  
115         if (contentHeader != null) {  
116             HeaderElement[] values = contentHeader.getElements();  
117             if (values.length == 1) {  
118                 NameValuePair param = values[0].getParameterByName("filename");  
119                 if (param != null) {  
120                     try {  
121                         //filename = new String(param.getValue().toString().getBytes(), "utf-8");  
122                         //filename=URLDecoder.decode(param.getValue(),"utf-8");  
123                         filename = param.getValue();  
124                     } catch (Exception e) {  
125                         e.printStackTrace();  
126                     }  
127                 }  
128             }  
129         }  
130         return filename;  
131     }  
132     /** 
133      * 获取随机文件名 
134      * @return 
135      */  
136     public static String getRandomFileName() {  
137         return String.valueOf(System.currentTimeMillis());  
138     }  
139     public static void outHeaders(HttpResponse response) {  
140         Header[] headers = response.getAllHeaders();  
141         for (int i = 0; i < headers.length; i++) {  
142             System.out.println(headers[i]);  
143         }  
144     }  
145     public static void main(String[] args) {  
146 //      String url = "http://bbs.btwuji.com/job.php?action=download&pid=tpc&tid=320678&aid=216617";  
147         String url="http://www.dy1000.com/img/20120701/1999311085_150_200.JPG";  
148 //      String filepath = "D:\\test\\a.torrent";  
149         String filepath = "D:\\test\\a.jpg";  
150         HttpDownload.download(url, filepath);  
151     }  
152 }  

 


参考资料: 
http://eyecm.com/httpclient4-1-tutorial-official-examples-to-explain-httpclient4-1-usage/ 
http://eyecm.com/httpclient-download/

posted @ 2016-11-11 14:07  正义的背叛  阅读(19570)  评论(1编辑  收藏  举报