java—如何在post请求中发送json和字符串作为请求体

mccptt67  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(244)

如何在post请求中同时发送json和string作为请求体?下面是我的代码

String prms = String.format("%s=%s&%s=%s&%s=%s&%s=%s",
            "aKey", "a123", "bKey", "b123",
            "cKey", "c123", "dKey", "d123");
JSONObject aInfo = new JSONObject(), jsonObj = new JSONObject();
aInfo.put("msg1", "123");
aInfo.put("msg2", "456");
jsonObj.put("obj", aInfo);
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(true);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream opStream = new DataOutputStream(connection.getOutputStream());
opStream.writeBytes(prms);
byte[] requestBody = jsonObj.toString().getBytes("utf-8");
opStream.write(requestBody);

我要走了 "error":{"code":400,"message":"Invalid JSON payload received. Unexpected token.\naKey\n^","errors":[{"reason":"parseError","domain":"global","message":"Invalid JSON payload received. Unexpected token.\naKey=1%2a123\n^"}],"status":"INVALID_ARGUMENT"}}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题