在Java中,我向JSON对象添加了一些属性,并将这些值发送到HTTPS URL(REST API)。服务器抛出诸如“无效的utf-8起始字节0xb0”之类的错误。下面是我的代码:
final String urlString = "https://connect.pointclickcare.com/api/public/preview1/orgs/"+vitalStat.get("customer")+"/observations";
String authorization = "Bearer "+vitalStat.get("accessToken");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", vitalStat.get("type"));
jsonObject.addProperty("patientId", patientInfo.getPatientId());
jsonObject.addProperty("deviceId", vitalStat.get("deviceId"));
jsonObject.addProperty("deviceName", vitalStat.get("deviceName"));
jsonObject.addProperty("recordedDate", vitalStat.get("recordedDate"));
jsonObject.addProperty("value", vitalStat.get("value"));
jsonObject.addProperty("method", vitalStat.get("method"));
if(vitalStat.get("type").equals("temperature"))
{
jsonObject.addProperty("unit", "°F");
}
else{
jsonObject.addProperty("unit", vitalStat.get("unit"));
}
if(vitalStat.get("type").equals("bloodPressure"))
{
String[] split = vitalStat.get("value").split("/");
jsonObject.addProperty("systolicValue", split[0]);
jsonObject.addProperty("diastolicValue", split[1]);
jsonObject.remove("value");
}
HttpURLConnection connection = null;
try {
final URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Authorization", authorization);
final OutputStream outputStream = connection.getOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.close();
System.out.println(connection.getResponseMessage());
答案 0 :(得分:1)
您不想使用DataOutputStream
。它具有自己的数据编码,并且肯定与JSON不兼容。相反,您必须序列化JSON数据,以便生成JSON的字符串表示形式(在UTF-8中)。
我假设您正在使用JsonObject
中的org.json
。在这种情况下,代码应如下所示:
final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);