我正在构建一个代码来调用Post Web Service。
因此,我无法添加JSON输入。
我的JSON输入必须是这样的:

{
  "patientId": 13,
  "timeType": 0,
  "date": "19/08/2019",
  "countryID" : "Central Europe Standard Time"
}


这是我的代码:

URL url = new URL("http://stgsd.appsndevs.com/AppCardioAPI/api/Resource/GetZephyrECGDataByPatientId");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");


if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
        + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));
ObjectMapper mapper = new ObjectMapper();
RRImportData parsed = mapper.readValue(conn.getInputStream(), RRImportData.class);


如何设置JSON输入对象?

最佳答案

请执行以下操作:

    RRImportData data = new RRImportData();
    data.setPatientId("abcd");
    //set othe attributes..

    URL url = new URL(
            "http://stgsd.appsndevs.com/AppCardioAPI/api/Resource/GetZephyrECGDataByPatientId");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Content-Type", "application/json");



    ObjectMapper mapper = new ObjectMapper();
    String payload = mapper.writeValueAsString(data);

    conn.setDoOutput(true);
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
    wr.write(payload);
    wr.flush();
    wr.close();

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));


在这里,首先我们将POJO RRImportData转换为String,然后将其作为有效载荷写入到POST请求中。 BufferedReader br可用于读取从服务器获得的响应。

10-06 07:00