问题:发送octet-stream格式Content-Type=application/octet-stream的请求,导致返回的消息中,中文也被编码成了octet-stream,无法直接解析,总是乱码
解决方案:给resttemplate的stringhttpmessageconverter设置charset
这里是设置charset
public RestTemplate createRestTemplate(SimpleClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> messageConverter : messageConverters) {
if (messageConverter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) messageConverter).setDefaultCharset(StandardCharsets.UTF_8);
}
}
return restTemplate;
}
private void Post(byte[] data) {
try {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(3000);
requestFactory.setReadTimeout(10000);
RestTemplate restTemplate=createRestTemplate(requestFactory);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Domain", "Domain");
headers.add("Content-Type", "application/octet-stream");
headers.add("Asr-Protocol", "1");
HttpEntity<byte[]> entity = new HttpEntity<>(data, headers);
ResponseEntity responseEntity = restTemplate.postForEntity(JDFinanceEngineTrans.RequestURL,entity, String.class);
if (responseEntity.getStatusCode() != org.springframework.http.HttpStatus.OK) {
log.error("Post result failed.status={}", responseEntity.getStatusCodeValue());
}
String result = responseEntity.getBody().toString();
log.info("JD ASR response:{}",result);
asrResults.add(result);
} catch (Exception ex) {
log.error("Post result failed.{}", ex.getMessage());
}
}