1. 程式人生 > >HttpClien實現使用post方式模擬表單上傳大檔案和字元引數

HttpClien實現使用post方式模擬表單上傳大檔案和字元引數

前提:自行準備好httpmime.jar

/**
 * HttpClien實現模擬表單post提交檔案資料和字元引數,並支援大檔案上傳
 * @author dance
 *
 */
public class HttpClientUploadManager {

	public interface HttpClientUploadResponse {
		int SUCCESS = 1;
		int FAIL = 0;
	}
	
	/**
	 * 該方式是支援大檔案上傳的,如果用HttpURLConnection一般只能上傳5M以內的,再大就OOM了
	 * @param handler activity宿主handler
	 * @param url 
	 * @param filepath 檔案路徑
	 * @param fileKey 檔案對應的key
	 * @param mapParams 字元引數的key和值封裝好傳入
	 */
	public static void upload(Handler handler, String url, String filepath,
			String fileKey, HashMap<String, String> mapParams) {
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		client.getParams().setParameter(
				CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");

		try {
			MultipartEntity entity = new MultipartEntity();
			// 檔案引數部分
			File file = new File(filepath);
			ContentBody fileBody = new FileBody(file); // file
			entity.addPart(fileKey, fileBody);
			// 字元引數部分
			Set<String> set = mapParams.keySet();
			for (String key : set) {
				entity.addPart(key, new StringBody(mapParams.get(key)));
			}
			httpPost.setEntity(entity);

			HttpResponse response = client.execute(httpPost);
			Message message = handler.obtainMessage();
			if (response.getStatusLine().getStatusCode() == 200) { // 成功
				//獲取伺服器返回值
				HttpEntity responseEntity = response.getEntity();
				InputStream input = responseEntity.getContent();
				StringBuilder sb = new StringBuilder();
				int s;
				while ((s = input.read()) != -1) {
					sb.append((char) s);
				}
				String result = sb.toString();
				LogUtil.i("HttpClientUploadManager", "http client upload result: " + result);
				message.what = HttpClientUploadResponse.SUCCESS;
				message.obj = result;//將資料返回給activity
			}else {
				message.what = HttpClientUploadResponse.FAIL;
			}
			handler.sendMessage(message);
		} catch (Exception e) {
			Message message = handler.obtainMessage();
			message.what = HttpClientUploadResponse.FAIL;
			handler.sendMessage(message);
		}
	}
}