When trying to send a JSON object to the server using POST method, "400 Bad request" error is returned. Standard Java application (SDK) with Restlet api is used to make this request.
Given that the:
here is how the code so far looks like:
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 }
Response from server is "400 Bad request". Here is the console output:
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)
When using Chrome POSTMAN plugin to send this json object (and it works with POSTMAN), the output of the POST request looks like this:
/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" }
Any suggestions on what may be wrong in the code? Thanks.
Solved it. You were right @Octopus, there was a problem in this code:
obj.put("partId", "23");
obj.put("carId", "34");
obj.put("name", "chassis");
obj.put("section", "frame");
It should look like (numbers without quotes):
obj.put("partId", 23);
obj.put("carId", 34);
obj.put("name", "chassis");
obj.put("section", "frame");
Thanks again both @Octopus and @Sotirios Delimanolis for your time and help.