更新时间:2023-01-17 08:36:03
您的JSON不正确。而不是
Your JSON is not correct. Instead of
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString()); // <-- toString()
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
写
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);
OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
因此,对于外部对象,JSONObject.toString()只能调用一次。
So, the JSONObject.toString() should be called only once for the outer object.
另一件事(很可能不是你的问题,但我想提一提):
Another thing (most probably not your problem, but I'd like to mention it):
要运行编码问题,应该指定编码,如果不是 UTF-8
:
To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8
:
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// ...
OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();