org.apache.http.client.methods.HttpPost 两种消息体形式 —— UrlEncodedFormEntity 和 StringEntity

一、UrlEncodedFormEntity

代码示例:

//设置请求方式与参数
URI uri = new URI(uriStr);
HttpPost httpPost = new HttpPost(uri);
httpPost.getParams().setParameter("http.socket.timeout", new Integer(500000));
httpPost.setHeader("Content-type", "text/plain; charset=UTF-8");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
httpPost.setHeader("IConnection", "close");

List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("KEY1", "VALUE1"));
//...
httpPost.setEntity(new UrlEncodedFormEntity(nvps));

//执行请求
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter("Content-Encoding", "UTF-8");
HttpResponse response = httpclient.execute(httpPost);

//获取返回
HttpEntity entity = response.getEntity();
BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
  buffer.append(line);
}
return buffer.toString();

使用 UrlEncodedFormEntity 来设置 body,消息体内容类似于“KEY1=VALUE1&KEY2=VALUE2&...”这种形式,服务端接收以后也要依据这种协议形式做处理。

二、StringEntity
有时候我们不想使用上述格式来传值,而是想使用json格式来设置body,就可以使用这个类的实例。

代码示例:

JSONObject jsonObject = new JSONObject();
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
httpPost.setEntity(new StringEntity(jsonObject.toString()));

其实,采用 StringEntity 就是形式比较自由了,除了json,你也可以使用其它任意的字符串,只要服务端能做相应处理即可

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值