我想用一些JSON数据向我的NodeJS / Express API发送POST请求。我设法毫无问题地发出GET请求。这是我为POST请求所做的事情:
URL u = new URL(url);
JSONObject jsonObject = new JSONObject();
jsonObject.put("nombre", "testing");
c = (HttpURLConnection) u.openConnection();
c.setDoOutput(true);
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", Integer.toString(URLEncoder.encode(jsonObject.toString(),"UTF-8").length()));
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(0);
c.setReadTimeout(0);
c.connect();
DataOutputStream printout = new DataOutputStream(c.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonObject.toString(),"UTF-8"));
printout.flush ();
printout.close ();
int status = c.getResponseCode();
在我的API中,我有一个console.log(req.body);
来查看我的POST路由是什么,这就是我在控制台中获得的内容:
Got this for POST:
{ '{"nombre":"testing"}': '' }
整个JSONObject作为JSON对象的密钥发送,在HTTP POST请求中具有空值。关于我做错什么的任何想法?谢谢!
答案 0 :(得分:1)
尝试替换
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
与
c.setRequestProperty("Content-Type", "application/json");
和
printout.writeBytes(URLEncoder.encode(jsonObject.toString(),"UTF-8"));
与
printout.writeBytes(jsonObject.toString());