一、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()));
可以看出,UrlEncodedFormEntity()的形式比较单一,只能是普通的键值对,局限性相对较大。
而StringEntity()的形式比较自由,只要是字符串放进去,不论格式都可以。