Java 使用Restlet通过POST发送JSON会导致;“400错误请求”;错误
尝试使用POST方法向服务器发送JSON对象时,返回“400错误请求”错误。使用带有Restlet api的标准Java应用程序(SDK)发出此请求 鉴于:Java 使用Restlet通过POST发送JSON会导致;“400错误请求”;错误,java,json,post,restlet,Java,Json,Post,Restlet,尝试使用POST方法向服务器发送JSON对象时,返回“400错误请求”错误。使用带有Restlet api的标准Java应用程序(SDK)发出此请求 鉴于: 主机地址为“” 访问密钥为“8QON4KC7BMayBCEX” 到目前为止,代码是这样的: ClientResource resource = new ClientResource("http://myhostname.com/api/v1/parts/"); resource.setMethod(Method.POS
- 主机地址为“”
- 访问密钥为“8QON4KC7BMayBCEX”
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插件发送此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");
它应该看起来像(没有引号的数字):
再次感谢@Octopus和@Sotirios Delimanolis为您提供的时间和帮助。这是真正的邮递员发帖请求吗?以下
“name”:机箱格式不正确。我没有看到StringRepresentation构造函数接受字符串对象?如果将json对象转换为字符串,则所有双引号都将用反斜杠转义。这可能会在邮递员中产生问题,json对象是手动添加的(“原始”选项卡)。现在我已经更新了。@OctopusString
是CharSequence
@Octopus的一个子类型,谢谢你的提示。然而,当在控制台中打印StringReprespantation对象时,它给出以下信息:{“partId”:“23”,“carId”:“34”,“name”:“chassis”,“section”:“frame”}。您的示例JSON:P误导了我们,使用重载的put
方法将生成“partId”:23
,而不是“partId”:“23”
。是的,我的错。抱歉误导:-)。谢谢。
obj.put("partId", 23);
obj.put("carId", 34);
obj.put("name", "chassis");
obj.put("section", "frame");