我正在尝试在进行Rest Api调用(POST)时传递Request body。使用以下代码:
String urlString ="url-string-of-api-call";
String body = "{\"type\":\"dog\",\"price\":249.99}";
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
OutputStream writer = conn.getOutputStream();
writer.write(body.getBytes());
writer.flush();
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
输出是:
{
"errors": [
{
"key": "Pet2.type",
"message": "Missing required field"
},
{
"key": "Pet2.price",
"message": "Missing required field"
}
]
}
这意味着“类型”和“价格”不会作为请求正文的一部分传递