【发布时间】:2014-01-10 08:07:58
【问题描述】:
当尝试使用 POST 方法向服务器发送 JSON 对象 时,返回“400 Bad request”错误。带有 Restlet api 的标准 Java 应用程序 (SDK) 用于发出此请求。
鉴于:
- 主机地址是“http://myhostname.com/api/v1/parts/”
- access_key 是“8QON4KC7BMAYYBCEX”
目前的代码如下所示:
ClientResource resource = new ClientResource("http://myhostname.com/api/v1/parts/");
resource.setMethod(Method.POST);
resource.getReference().addQueryParameter("format", "json");
resource.getReference().addQueryParameter("access_key", "8QON4KC7BMAYYBCEX");
// create json object and populate it
JSONObject obj = new JSONObject();
try {
obj.put("partId", "23");
obj.put("carId", "34");
obj.put("name", "chassis");
obj.put("section", "frame");
} catch (JSONException e1) {// handling of exception}
StringRepresentation stringRep = new StringRepresentation(obj.toString());
stringRep.setMediaType(MediaType.APPLICATION_JSON);
try {
resource.post(stringRep).write(System.out); // exception occurs here
} catch (Exception e) {// handling of exceptions }
来自服务器的响应是“400 Bad request”。这是控制台输出:
Bad Request (400) - BAD REQUEST
at org.restlet.resource.ClientResource.doError(ClientResource.java:612)
at org.restlet.resource.ClientResource.handleInbound(ClientResource.java:1202)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1069)
at org.restlet.resource.ClientResource.handle(ClientResource.java:1044)
at org.restlet.resource.ClientResource.post(ClientResource.java:1453)
at tests.RESTTestReceiverPOST.main(RESTTestReceiverPOST.java:39)
当使用 Chrome POSTMAN 插件发送这个 json 对象(它与 POSTMAN 一起使用)时,POST 请求的输出如下所示:
/api/v1/parts/?format=json&access_key=8QON4KC7BMAYYBCEX HTTP/1.1
Host: myhostname.com
Content-Type: application/json
{ "partId": "23", "carId": "34", "name": "chassis", "section": "frame" }
对代码中可能有什么问题有什么建议吗?谢谢。
【问题讨论】:
-
这是实际的 POSTMAN 发布请求吗?以下
"name": chassis格式不正确。 -
我没有看到 StringRepresentation 构造函数采用 String 对象?如果将 json 对象转换为字符串,则所有双引号都将使用反斜杠进行转义。这可能会产生问题
-
在 POSTMAN 中,手动添加 json 对象(“原始”选项卡)。现在我已经更新了。
-
@Octopus
String是CharSequence的子类型。 -
@Octopus 感谢您的提示。但是,当在控制台中打印 StringRepresantation 对象时,它会给出: { "partId": "23", "carId": "34", "name": "chassis", "section": "frame" }