一、UrlEncodedFormEntity
代码示例:
//设置请求方式与参数
URI uri = new URI(uriStr);
HttpPost httpPost = new HttpPost(uri);
().setParameter("", new Integer(500000));
("Content-type", "text/plain; charset=UTF-8");
("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
("IConnection", "close");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
(new BasicNameValuePair("KEY1", "VALUE1"));
//...
(new UrlEncodedFormEntity(nvps));
//执行请求
HttpClient httpclient = new DefaultHttpClient();
().setParameter("Content-Encoding", "UTF-8");
HttpResponse response = (httpPost);
//获取返回
HttpEntity entity = ();
BufferedReader in = new BufferedReader(new InputStreamReader((), "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = ()) != null) {
(line);
}
return ();
使用 UrlEncodedFormEntity 来设置 body,消息体内容类似于“KEY1=VALUE1&KEY2=VALUE2&...”这种形式,服务端接收以后也要依据这种协议形式做处理。
二、StringEntity
有时候我们不想使用上述格式来传值,而是想使用json格式来设置body,就可以使用这个类的实例。
代码示例:
JSONObject jsonObject = new JSONObject();
("KEY1", "VALUE1");
("KEY2", "VALUE2");
(new StringEntity(()));
其实,采用 StringEntity 就是形式比较*了,除了json,你也可以使用其它任意的字符串,只要服务端能做相应处理即可。
原文链接:/xuleo/blog/1491669