MultipartEntity与UrlEncodedFormEntity

html中的form 表单有两种:除了传统的application/x-www-form-urlencoded表单,我们另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data。  后者主要是用来上传文件所用,所以一般情况下,在使用webservice 时,使用UrlEncodedFormEntity 比较多,UrlEncodedFormEntity 可以模拟传统的HTML表单传送POST请求中的参数,

如:html表单如下:

<form action=”http://localhost/index.html” method=”POST”>
<input type=”text” name=”param1″ value=”李三”/>
<input type=”text” name=”param2″ value=”男”/>
<inupt type=”submit” value=”submit”/>
</form>

 

代码如下:

List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair(“param1″, “李三”));
formParams.add(new BasicNameValuePair(“param2″, “男”));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, “UTF-8″);

MultipartEntity  则与form类型为multipart/form-data 对应,如 html from 如下:

 

<form action=”http://localhost/index.html” method=”POST”
enctype=”multipart/form-data”>
<input type=”text” name=”param1″ value=”李三”/>
<input type=”text” name=”param2″ value=”男”/>
<input type=”file” name=”param3″/>
<inupt type=”submit” value=”submit”/>
</form>

代码如下:

MultipartEntity entity = new MultipartEntity();
entity.addPart(“param1″, new StringBody(“李三”, Charset.forName(“UTF-8″)));
entity.addPart(“param2″, new StringBody(“男”, Charset.forName(“UTF-8″)));
entity.addPart(“param3″, new FileBody(new File(“C:\\pic.gif”)));

/*
   org.apache.http.entity.mime.content.FileBody.FileBody
   org.apache.http.client.methods.HttpPost.HttpPost
   org.apache.http.entity.mime.MultipartEntityBuilder
   org.apache.http.client.methods.CloseableHttpResponse
   org.apache.http.HttpEntity
*/
CloseableHttpResponse response = null;
HttpEntity entity = null;
String result = null;
try {
	FileBody bin = new FileBody(uploadImgRequest.getFile());
	HttpPost httpPost = new HttpPost(uploadImgRequest.getUrl());
	HttpEntity reqEntity = MultipartEntityBuilder.create()
	.addPart("buffer", bin)
	.addTextBody("access_token", uploadImgRequest.getAccess_token())
	.build();
	httpPost.setEntity(reqEntity);
	response = httpClient.execute(httpPost);
	entity = response.getEntity();
	if (entity != null) {
		result = EntityUtils.toString(entity, "utf-8");
	}
	int statusCode = response.getStatusLine().getStatusCode();
	if (statusCode != 200) {
		httpPost.abort();
		throw new RuntimeException("HttpClient,error status code :"
				+ statusCode+",result:"+result);
	}
}

 

转载于:https://my.oschina.net/u/2369810/blog/604025

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值