如何在 Spring Boot 中使用 Rest 客户端处理 �

问题描述 投票:0回答:1
这些是我的数据类

@JsonIgnoreProperties data class Tri4Data( @JsonProperty("Status") val status: String, @JsonProperty("data") val data: Tri4JsonData ) @JsonIgnoreProperties data class Tri4JsonData( @JsonProperty("children") val children: List<Tri4Children> ) data class Tri4Children( @JsonProperty("ID") val id: Int, @JsonProperty("Code") val code: String, @JsonProperty("Description") val description: String?, @JsonProperty("Gender") val gender: String?, @JsonProperty("Initials") val initials: String?, @JsonProperty("Surname") val surname: String?, @JsonProperty("Pracno") val pracNum: String? )
这是我的 API 请求

restTemplate.exchange(url, HttpMethod.GET, httpEntity, Tri4Data::class.java).body
这是我收到的错误,我假设它来自 API 调用中的此响应:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 start byte 0x86
回应

{ "ID": 27203, "Code": "G73.1", "Description": "Lambert-Eaton syndrome (C00-D48�) " },
    
json spring-boot kotlin resttemplate
1个回答
0
投票
你能打印响应头吗?

当我尝试使用最新的 Spring Boot 应用程序(3.2.3)时,只有当服务器显式返回 header

'Content-type', 'application/json; charset=utf-8'

(但随后返回此 UTF-8 无效字节)时,我才会出现此行为。如果标头不存在,我会收到不同的错误。因此,我假设您要访问的服务器传达 
Content-Type
UTF-8
 但继续返回无效字节作为其响应的一部分。

0x86

似乎来自
windows-1252
(或类似)并代表

也许,您正在通信的服务器是“行为良好”的,如果您指定接受

UTF-8

,它会在
UTF-8
中返回它。您可以通过以下方式实现这一目标:

HttpHeaders headers = new HttpHeaders(); headers.set("Accept-Encoding", "application/json;charset=UTF-8"); HttpEntity<...> httpEntity = new HttpEntity<>(headers); // and use this in restTemplate.exchange
如果您要与遗留(因此无法更改)和行为不良的服务器集成,那么另一种非标准的可能性是实现和注册自定义 

HttpMessageConverter

 ,它将接受 
UTF-8
 编码,但在内部处理它是
windows-1252
。 (
请参阅此问题了解上下文

话虽这么说,正如上面评论中指出的

- RFC-8259 指出,JSON 应该编码为 UTF-8。此 JSON 不符合该要求,因为它包含无效的

UTF-8
编码字符串的字符串字段。
但是根据 

closed ecosystem

的定义,存在(错误)解释的空间:


在不属于封闭系统的系统之间交换的 JSON 文本 生态系统必须使用 UTF-8 编码

© www.soinside.com 2019 - 2024. All rights reserved.