2016-08-21 58 views
1

谁能能告诉我,与示例代码:如何发布JSON的REST Web服务在codenameone

  1. 如何发布JSON一个REST Web服务;和

  2. 如何从服务器读取JSON响应;

使用Codename One?

这是我已经试过这回从服务器坏请求响应:

 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(); 
       } 
      } 
     }); 
+0

SO既不是代码编写,也没有功课辅导,和你的紧迫性在这里无关紧要。你的代码在哪里,它有什么问题?见[问]。 – jonrsharpe

+0

好的,谢谢,我编辑了我的问题 – user3855323

+0

给一个[mcve] - 如果他们不知道一个好的回答应该是什么样子,谁能帮助? – jonrsharpe

回答

2

postResponse()过程完成后调用。与帖子本身无关。您想覆盖之前执行的buildRequestBody。如果我理解正确你想整个身体是JSON,而不是一个参数命名为“体”,这是你做了什么...:

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"); 
+0

非常感谢你shai,它真的解决了我现在可以发布和接收数据到服务器的问题。再次感谢 – user3855323