【问题标题】:Sending JSON by POST using Restlet results in "400 Bad request" error使用 Restlet 通过 POST 发送 JSON 会导致“400 Bad request”错误
【发布时间】:2014-01-10 08:07:58
【问题描述】:

当尝试使用 POST 方法向服务器发送 JSON 对象 时,返回“400 Bad request”错误。带有 Restlet api 的标准 Java 应用程序 (SDK) 用于发出此请求。

鉴于:

目前的代码如下所示:

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 StringCharSequence 的子类型。
  • @Octopus 感谢您的提示。但是,当在控制台中打印 StringRepresantation 对象时,它会给出: { "partId": "23", "carId": "34", "name": "chassis", "section": "frame" }

标签: java json post restlet


【解决方案1】:

解决了。你是对的@Octopus,这段代码有问题:

   obj.put("partId", "23");
   obj.put("carId", "34");
   obj.put("name", "chassis");
   obj.put("section", "frame");

它应该看起来像(不带引号的数字):

obj.put("partId", 23);
obj.put("carId", 34);
obj.put("name", "chassis");
obj.put("section", "frame");

再次感谢 @Octopus 和 @Sotirios Delimanolis 的宝贵时间和帮助。

【讨论】:

  • 您的示例 JSON 误导了我们:P 使用重载的 put 方法将生成 "partId" : 23 而不是 "partId" : "23"
  • 是的,我的错。抱歉误导:-)。非常感谢。
猜你喜欢
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
相关资源
最近更新 更多