UrlEncodedFormEntity和StringEntity:HttpPost 两种消息体形式

一、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 nvps = new ArrayList();
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,你也可以使用其它任意的字符串,只要服务端能做相应处理即可。

原文链接:https://my.oschina.net/xuleo/blog/1491669 

你可能感兴趣的:(HTTP)