如何在后api调用java中传递请求体

时间:2017-11-12 13:05:33

标签: java rest httpsurlconnection

我正在尝试在进行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"
    }
  ]
}

这意味着“类型”和“价格”不会作为请求正文的一部分传递

0 个答案:

没有答案