1. 程式人生 > >【java】HttpClient實現HTTP檔案通用下載工具類

【java】HttpClient實現HTTP檔案通用下載工具類

package com.imopan.cps.apart.api.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 *  
 *  HttpClient實現HTTP檔案通用下載類
 *  maven依賴
 * <dependency>
 *	<groupId>org.apache.httpcomponents</groupId>
 *	<artifactId>httpclient</artifactId>
 *	<version>4.0.1</version>
 * </dependency>
 *  可下載http檔案、圖片、壓縮檔案
 *  bug:獲取response header中Content-Disposition中filename中文亂碼問題
 *  @author yuanjianqiang
 *
 */
public class HttpUtil {

	public static final int cache = 10 * 1024;
	public static final boolean isWindows;
	public static final String splash;
	public static final String root;
	static {
		if (System.getProperty("os.name") != null && System.getProperty("os.name").toLowerCase().contains("windows")) {
			isWindows = true;
			splash = "\\";
			root="D:";
		} else {
			isWindows = false;
			splash = "/";
			root="/search";
		}
	}
	
	/**
	 * 根據url下載檔案,檔名從response header頭中獲取
	 * @param url
	 * @return
	 */
	public static String download(String url) {
		return download(url, null);
	}

	/**
	 * 根據url下載檔案,儲存到filepath中
	 * @param url
	 * @param filepath
	 * @return
	 */
	public static String download(String url, String filepath) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = client.execute(httpget);

			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			if (filepath == null)
				filepath = getFilePath(response);
			File file = new File(filepath);
			file.getParentFile().mkdirs();
			FileOutputStream fileout = new FileOutputStream(file);
			/**
			 * 根據實際執行效果 設定緩衝區大小
			 */
			byte[] buffer=new byte[cache];
			int ch = 0;
			while ((ch = is.read(buffer)) != -1) {
				fileout.write(buffer,0,ch);
			}
			is.close();
			fileout.flush();
			fileout.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 獲取response要下載的檔案的預設路徑
	 * @param response
	 * @return
	 */
	public static String getFilePath(HttpResponse response) {
		String filepath = root + splash;
		String filename = getFileName(response);

		if (filename != null) {
			filepath += filename;
		} else {
			filepath += getRandomFileName();
		}
		return filepath;
	}
	/**
	 * 獲取response header中Content-Disposition中的filename值
	 * @param response
	 * @return
	 */
	public static String getFileName(HttpResponse response) {
		Header contentHeader = response.getFirstHeader("Content-Disposition");
		String filename = null;
		if (contentHeader != null) {
			HeaderElement[] values = contentHeader.getElements();
			if (values.length == 1) {
				NameValuePair param = values[0].getParameterByName("filename");
				if (param != null) {
					try {
						//filename = new String(param.getValue().toString().getBytes(), "utf-8");
						//filename=URLDecoder.decode(param.getValue(),"utf-8");
						filename = param.getValue();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return filename;
	}
	/**
	 * 獲取隨機檔名
	 * @return
	 */
	public static String getRandomFileName() {
		return String.valueOf(System.currentTimeMillis());
	}
	/**
	 * 獲取response header
	 * @param response
	 */
	public static void outHeaders(HttpResponse response) {
		Header[] headers = response.getAllHeaders();
		for (int i = 0; i < headers.length; i++) {
			System.out.println(headers[i]);
		}
	}
	public static void main(String[] args) {
//		String url = "http://bbs.btwuji.com/job.php?action=download&pid=tpc&tid=320678&aid=216617";
		String url="http://api.gfan.com/market/api/apk?type=WAP&cid=99&uid=-1&pid=1h78UtiFQv4ioruN/Z7gWW+iLrL+AjG7&sid=PEHHOSpUGP1hfoViijqdTQ==";
//		String filepath = "D:\\test\\a.torrent";
		String filepath = "D:\\test\\a.apk";
		HttpUtil.download(url, filepath);
	}
}