在做安卓端向服务器使用 http 请求数据时,使用post方式,并且需要传递参数。遇到的问题 及 解决方法如下:
起初,我使用了 UrlEncodedFormEntity() 这个方法,但是后台报错,无法解析json内容;
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
这是后台获取到的请求参数:
json=%7B%22agentId%22%3A%2223333%22%2C%22accessKey%22%3A%22Gaizuojia%22%7D
其实是键值对,并不是json数据;
查找原因后,改为使用 StringEntity() 方法,后台能够获取到请求参数,并解析成功;
httpPost.setEntity(new StringEntity(json,"utf-8"));
这是后台获取到的请求参数:
{"agentId":Chitty,"accessKey":tinaahsd}
这就是正确的json数据;
查看API 后知道 类StringEntity 的 直接已知子类是 UrlEncodedFormEntity ;
UrlEncodedFormEntity 是模拟form表单的形式;而 StringEntity 的数据组织形式更加灵活,是单纯的一种传值容器。
更多可参考
http://blog.youkuaiyun.com/zhouyingge1104/article/details/41488313