我正在尝试使用 Java 将 JSON 格式的数据发送到服务器。信息正在到达服务器,但服务器正在响应“错误请求”。
HttpPost httpost = new HttpPost(path);
StringEntity se = new StringEntity(JSONRequest);
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json;charset=utf8");
HttpResponse response = httpclient.execute(httpost);
这是我请求的基本设置。这是 JSONData:
{"clientApplicationDto":{"AuthenticationToken":"","BrandId":12,"MobileDeviceApplicationId":0},"mobileDeviceInfo":{"CarrierName":"MTN-SA","OsVersion":"2.2.2","ClientApplicationVersion":"TEST","DeviceManufacturer":"HTC","DeviceName":"HTC Desire","DeviceUniqueId":"1e9766fa2ef4c53a","OsName":"8","ClientApplicationTypeId":3}}
如果你们觉得这很合适,我将开始向管理员发送垃圾邮件,但现在,我需要知道我是否遗漏了什么。
最佳答案
我发现了问题...服务器对内容类型 header 和内容格式极其敏感
httpost.setHeader("Content-type", "application/json;charset=utf8");
需要改成
httpost.setHeader("Content-type", "application/json; charset=utf-8");
和 StringEntity se = new StringEntity(JSONRequest);
需要改成
StringEntity se = new StringEntity(JSONRequest,"utf-8");
谢谢 Jens,那条评论将我推向了正确的方向。
关于Java:预览 HttpPost 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972627/