如何通过Codename one API发出JSON PUT请求

时间:2016-07-18 00:17:31

标签: json codenameone

我无法从代号为api的数字中找出JSON提出的请求。我没有找到任何例子来提出这个请求。

问题: 1.我不确定是否必须发送内容长度参数。如果是的话,我该如何发送? 我必须发送请求正文" true"没有其他的。使用req.addArgument()方法没有关键和价值。 3.我是否必须使用buildRequestBody()方法来覆盖请求。你能提供一个例子吗? 4.如何在收到回复后验证结果。

任何帮助都可以得到赞赏。 感谢。

请找到以下代码。

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 个答案:

答案 0 :(得分:0)

如果您希望完全嵌入内容,则需要覆盖buildRequestBody方法。请注意,对于要调用的主体,post必须为true。

我认为您不需要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);

请注意,我不再需要关闭流或处理IOException,因为连接请求会为我完成所有操作。另请注意,读取/构建方法是在网络线程上调用的,而不是在EDT上调用,因此您需要在postResponse中完成剩余的流程。

相关问题