android手机端需要发送一个json格式的数据,返回的也是json数据。
现在问题出现在,我无论怎么写都返回400,Bad Request。
问题出在哪儿呢?且看代码,感觉该设置的都设置了。
[code="java"]
/**
* POST获取服务端数据,发送的是json格式的数据
* @param urlString
* @param json 需要发送的json数据
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public String getDataFromServerByPostForJson(String urlString,JSONObject json) throws ClientProtocolException, IOException{
String strResult = null;
HttpClient client = new DefaultHttpClient();
StringEntity entity = new StringEntity(json.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));//"application/octet-stream"
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING,HTTP.UTF_8));
HttpPost post = new HttpPost(urlString);
post.setHeader("Accept", "application/json");
post.setHeader("Content-Type", "application/json");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
strResult = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
}else{
post.abort();
strResult = "Error Response code "
+ response.getStatusLine().getStatusCode() + " :"
+ response.getStatusLine().toString();
Log.i("tag", strResult);
return null;
}
return strResult;
}
[/code]
有碰到类似的朋友吗?
发送请求的参数与后台 处理程序 的要求不匹配。
特别是用 spring mvc时,容易出现该问题。
比如
@RequestMapping("/api/ddd")
public @ResponseBody JsonResult
doDummy(@RequestParam("tid')Long id) {
.....
return result;
}
如果发送的url是
http://www.foo.com/api/ddd
没有参数,则400
发送请求
http://www.foo.com/api/ddd?id=2323
因为实际要求的参数是tid不是id,还是会出400错
在浏览器上直接访问可以吗?
是不是因为 entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));//"application/octet-stream"与下面的post.setHeader("Content-Type", "application/json"); 有冲突问题。都改成application/json试一下。
把那些头干掉,根本不用那些东西,直接就能发送
你的urlString是怎么样的?android模拟器桥接的局域网访问主机不是机器本身的局域网,我记得好像是10.0.2.2访问主机的