【发布时间】:2021-08-11 20:48:02
【问题描述】:
我在使用 REST API 时遇到问题。下面是我的休息客户。它在服务调用中失败并出现错误:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
at [Source: java.io.PushbackInputStream@62a8dd06; line: 11, column: 55]
当我在邮递员中使用相同的 json 字符串(打印在日志中)时,它可以工作。当我从客户端发出请求时它失败了。
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + base64Creds);
try {
request = mapper.constructRequest(txnRequest, params);
logger.debug(method + " Request: " + request);
ObjectMapper map = new ObjectMapper();
logger.debug(method + " Request in json format: " +
map.writeValueAsString(request));
myRequest = new HttpEntity<MyRequest>(request, headers);
response = restTemplate.exchange(url, HttpMethod.POST, myRequest, MyResponse.class);
logger.debug(method + " response: " + response);
} catch(Exception ex) {
ex.printStackTrace();
}
非常感谢任何帮助。
【问题讨论】:
-
字符代码 10(在 ascii 或几乎任何其他字符集中)是换行符,因此问题可能是在某处插入了意外的换行符。
-
感谢克里斯的回复。我切换到传统的 HttpURLConnection 来完成这项工作。通过这种方式,我可以使用 utf-8 设置输入和输出格式,并且可以正常工作。我尝试对休息模板做同样的事情,但问题仍然存在。所以,我想将我的客户端实现切换到 HttpURLConnection。
标签: rest-client jsonparser spring-resttemplate