user3855323 user3855323 - 3 months ago 56
reST (reStructuredText) Question

How to post JSON to a REST webservice in codenameone

Can anyone can show me, with sample codes:


  1. how to post JSON to a REST webservice; and

  2. how to read the JSON response from the server;



using Codename One?

Here is what i have tried which is returning bad request response from the server:

Button b1 = new Button("Add Staff");
b1.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent evt) {
JSONObject json = new JSONObject();
try {

ConnectionRequest post = new ConnectionRequest(){
@Override
protected void postResponse() {

try {

json.put("firstname", fname.getText());
json.put("middlename", mname.getText());
json.put("lastname", lname.getText());
json.put("dob", dob.getText());
json.put("gender", gender.getSelectedItem().toString());
json.put("marital", marital.getSelectedItem().toString());
json.put("phone", phone.getText());
json.put("adds", adds.getText());
json.put("username", user.getText());
json.put("password", pass.getText());
json.put("lat", lat.getText());
json.put("long", lon.getText());


} catch (JSONException ex) {
ex.printStackTrace();
}
}

@Override
protected void readResponse(InputStream input) throws IOException {

}

};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("APPLICATION/JSON");
post.addArgument("body", json.toString());


boolean show = Dialog.show("Add Staff", "Are you Sure you want to add this Staff", "Yes", "NO");
NetworkManager.getInstance().addToQueueAndWait(post);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(post.getResponseData()), "UTF-8"));
Map<String, Object> response = (Map<String, Object>)result.get("response");
Dialog.show("Staff Saved", ""+response, "OK","");



} catch (Exception ex) {
ex.printStackTrace();

}

}
});

Answer

postResponse() is invoked after the process completes. Not related to post itself. You want to override buildRequestBody which executes before. If I understand correctly you want the entire body to be the JSON and not an argument named "body" which is what you did...:

ConnectionRequest post = new ConnectionRequest(){
    @Override
    protected void buildRequestBody(OutputStream os) throws IOException {
        os.write(json.toString().getBytes("UTF-8"));
    }

    @Override
    protected void readResponse(InputStream input) throws IOException {
       // parse response data
    }
};
post.setUrl("http://localhost:8093/halimatbank/cbs/staff");
post.setPost(true);
post.setContentType("application/json");