【发布时间】:2012-01-23 13:47:09
【问题描述】:
我正在尝试使用 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}}
如果你觉得这很合适,我会开始向管理员发送垃圾邮件,但现在,我需要知道我是否遗漏了什么。
【问题讨论】:
-
Hm.. 对于初学者,
StringEntity(或者更确切地说是任何AbstractHttpEntity子类)有一个内容类型,默认情况下它将设置为常量HTTP.PLAIN_TEXT_TYPE,使用HTTP.DEFAULT_CONTENT_CHARSET作为字符集。考虑通过调用se#setContentType("application/json;charset=utf-8")来设置您的内容类型。顺便说一句,您的 JSON 看起来格式正确。 -
只是为了检查帖子或 java 代码是否有问题,您是否尝试过类似 Chrome REST 控制台的请求? chrome.google.com/webstore/detail/…