我正在尝试使用Codename One发送带有JSON BODY的POST请求。 以下是建立连接并发送消息的代码
ByteArrayOutputStream bOutput = new ByteArrayOutputStream();
bOutput.write("{\"Key1\": \"Value1\",\"Key2\": \"Value2\"}".getBytes());
try {
connectAction connReq = new connectAction();
connReq.setPost(true);
connReq.addRequestHeader("Authorization", "1234");
connReq.addRequestHeader("client_id","4321");
connReq.addRequestHeader("Content-Type","application/json");
connReq.setUrl("https://myapi.com/test");
connReq.setHttpMethod("POST");
connReq.buildRequestBody(bOutput);
NetworkManager.getInstance().addToQueueAndWait(connReq);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(connReq.getResponseData()), "UTF-8"));
return result;
}
catch(Exception err) {
System.err.println(err);
return null;
}
这是带有buildRequestBody覆盖的派生类
public class connectAction extends ConnectionRequest
{
connectAction()
{
}
@Override
public void buildRequestBody(OutputStream os)
{
}
}
现在,当我在public void buildRequestBody(OutputStream os)中放置断点时,我可以看到'os'具有值
os =(java.io.ByteArrayOutputStream){“Key1”:“Value1”,“Key2”:“Value2”}
所以我知道这个价值一直都是如此。
但是,当我启动网络监视器时,只会填充请求标头并且标头为空。
真正感谢任何帮助。
谢谢
答案 0 :(得分:2)
尝试以下代码希望它会有所帮助
// convert the object to a JSON document
HashMap hashtable = new HashMap ();
hashtable.put("Key1", "Value1");
hashtable.put("Key2", "Value2");
final String payload = Result.fromContent(hashtable).toString();
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(payload.getBytes("UTF-8"));
}