Android中模拟post表单提交,带参数及文件参数

有时候需要通过Android客户端向服务器提交数据,带一些参数、图片或其他文件,那么可以用如下方法,模拟post提交

例如网页中有个表单,如下

<form action="xxx.action" method="post" enctype="multipart/form-data">
   <input type="text" name="name" /><br />
   <input type="file" name="file" /><br />
   <input type="submit" />
</form>

我们可以在Android客户端模拟post方式提交,以达到上面的效果

	/**
	 * 提交数据
	 * @param url 服务端地址
	 * @param param 参数集合
	 * @param file 图片文件
	 * @param cookie 登录后返回的cookie,无登录验证可为null
	 * @return 服务器返回结果
	 * @throws Exception
	 */
	public static String uploadSubmit(String url, Map<String, String> param,
			File file, String cookie) throws Exception {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		if(cookie != null && cookie.length()>0){
			//向头信息添加cookie
			post.addHeader("cookie", cookie);
		}
		MultipartEntity entity = new MultipartEntity();
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				if (entry.getValue() != null
						&& entry.getValue().trim().length() > 0) {
					entity.addPart(entry.getKey(),
							new StringBody(entry.getValue()));
				}
			}
		}
		if (file != null && file.exists()) {
			entity.addPart("file", new FileBody(file));
		}
		post.setEntity(entity);
		HttpResponse response = httpClient.execute(post);
		int stateCode = response.getStatusLine().getStatusCode();
		StringBuffer sb = new StringBuffer();
		if (stateCode == HttpStatus.SC_OK) {
			HttpEntity result = response.getEntity();
			if (result != null) {
				InputStream is = result.getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String tempLine;
				while ((tempLine = br.readLine()) != null) {
					sb.append(tempLine);
				}
			}
		}
		post.abort();
		return sb.toString();
	}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值