您的位置:首页 > 理论基础 > 计算机网络

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

2017-07-28 16:46 489 查看
一、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,你也可以使用其它任意的字符串,只要服务端能做相应处理即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐