DefaultHttpClient HTTP 请求参数设置问题

HTTP请求方法很多,此处使用DefaultHttpClient 请求 全路径 org.apache.http.impl.client.DefaultHttpClient

设置请求的头部

HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "bearer ");
post.setHeader("Content-Type", "application/json");

设置body的几种方式对照

①使用UrlEncodedFormEntity

List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("userName", "123456");
NameValuePair pair2 = new BasicNameValuePair("password", "123456");
pairs.add(pair1);
pairs.add(pair2);

httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));

用UrlEncodedFormEntity()方法组织的数据发送到服务器却是如下形式:userName=123456&password=123456&......

②使用StringEntity

JSONObject json = new JSONObject();
json.put("userName", "123456"); 
json.put("password", "123456"); 
httpPost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));

使用StringEntity 发送个服务器格式是json格式的 {"userName":"123456","password":"123456"}

在ContentType 为"application/json"是 使用这种方式, 第一种可能为报错 请求失败

StringEntity 相对来说比较灵活,建议使用。

 

posted on 2015-09-22 19:13  Venetian  阅读(1784)  评论(0)    收藏  举报