繁体   English   中英

使用Restlet通过POST发送JSON会导致“ 400错误的请求”错误

[英]Sending JSON by POST using Restlet results in “400 Bad request” error

尝试使用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 (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" }

关于代码中可能有什么错误的任何建议? 谢谢。

解决了。 您说得对@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的时间和帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM