在 Android 中使用 HttpURLConnection 将整个 JSON对象作为 JSON 键发送
Whole JSONObject sent as JSON key using HttpURLConnection in Android
我想用一些 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"}': '' }
整个 JSON 对象在 HTTP POST 请求中作为空值 JSON 对象的键发送。关于我做错了什么的任何想法?谢谢!
尝试替换
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());
我想用一些 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"}': '' }
整个 JSON 对象在 HTTP POST 请求中作为空值 JSON 对象的键发送。关于我做错了什么的任何想法?谢谢!
尝试替换
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());