gpt4 book ai didi

java - 如何在JAVA客户端添加JSON输入

转载 作者:行者123 更新时间:2023-12-02 01:25:42 25 4
gpt4 key购买 nike

我正在构建一个代码来调用 Post Web 服务。所以我无法添加 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 转换为字符串,然后将其作为有效负载写入您的 POST 请求。 BufferedReader br可用于读取从服务器获得的响应。

关于java - 如何在JAVA客户端添加JSON输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57587942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com