1
votes

I'm not able top figure out JSON put request from codename one api. I didnt find any example to make this request.

Questions: 1. I'm not sure whether I have to send the content length parameter. If yes, how can I send that? 2. I have to send the request body with just "true" nothing else. There is no key and value to use req.addArgument() method. 3. Do I have to use buildRequestBody() method to override the request. Can you provide an example? 4. How to verify the result after receiving the response.

Any help can be appreciated. Thanks.

Please find the code below.

req.setUrl(identityUrl );
req.setPost(false);
req.setHttpMethod("PUT");               
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.addArgument("Content-Length", "4");
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
JSONParser parser = new JSONParser();
Map map2 = null;
try {
map2 = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(req.getResponseData()), "UTF-8"));
} catch (IOException ex) {
       ex.printStackTrace();
}
1

1 Answers

0
votes

If you want the content to be embedded wholly you need to override the buildRequestBody method. Notice that post needs to be true for the body to be called.

I don't think you need content-length:

req = new ConnectionRequest(identityUrl) {
   protected void buildRequestBody(OutputStream os) throws IOException {
        os.write(json.getBytes("UTF-8"));
   }

   protected void readResponse(InputStream input) throws IOException  {
      map2 = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
   }

   protected void postResponse() {
      // response completed, this is called on the EDT do the application logic here...
   }
};
req.setPost(true);
req.setHttpMethod("PUT");               
req.setContentType("application/json");
req.addRequestHeader("authorization", token);
req.setReadResponseForErrors(true);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
req.setDisposeOnCompletion(d);
NetworkManager.getInstance().addToQueue(req);

Notice that I no longer need to close streams or handle IOException as the connection request does everything for me. Also notice the read/build methods are called on the network threads and not on the EDT so you need to do the rest of the flow in the postResponse.