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);
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值