[英]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.