简体   繁体   中英

invalid utf-8 start byte 0xb0

In Java, I am adding some properties to a JSON object, and sending those values to an HTTPS URL (REST API). The server throws some error like "invalid utf-8 start byte 0xb0". Below is my code:

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());

You don't want to use DataOutputStream . It has its own data encoding and is certainly not compatible with JSON. Instead, you have to serialize your JSON data such that a string representation of JSON (in UTF-8) is generated.

I assume that you are using JsonObject from org.json . In that case, the code should looks something like this:

final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM