任何人都可以通过示例代码向我展示:
如何将JSON
发布到REST Web服务;以及
如何阅读服务器的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 :(得分:2)
postResponse()
。与帖子本身无关。您想要覆盖之前执行的buildRequestBody
。如果我理解正确,你希望整个身体都是JSON,而不是一个名为“body”的参数,这就是你所做的......:
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");