我有一个构建在Spring3.2.0上的Java应用程序,它执行对为JSON数据提供服务的REST的外部调用。
调用由Spring RestTemplate类执行,Jackson 2.2.3作为序列化程序/反序列化器。
该调用是功能性的,支持简单的和压缩的响应。
为了测试调用,我使用了MockRestServiceServer.一切都很好,直到我尝试引入gzip压缩。我无法在官方文档中找到如何在MockRestServiceServer中激活gzip压缩,因此我选择了手动路径:
不幸的是,我一次又一次地得到同样的错误,在反序列化响应体时由Jackson抛出:
org.springframework.http.converter.HttpMessageNotReadableException:无法读取JSON:非法字符((CTRL,代码31)):只有常规空白(\r,\n,\t)允许在源: java.io.ByteArrayInputStream@110d68a;行: 1,列: 2;嵌套异常是com.fasterxml.jackson.core.JsonParseException:非法字符(CTRL-CHAR,代码31):只允许在令牌之间使用常规空白(\r,\n,\t)
以下是当前代码(由于公司数据而重新工作)
测试类
公共类ImportRefCliCSTest { @Autowired私有MyService myService;私有MockRestServiceServer mockServer;@ new public void gzip(){ mockServer =MockRestServiceServer} @Test public void testExternalCall()引发IOException { String jsonData =“{\”Test\“:\”“Hurray!\”};HttpHeaders headers =新HttpHeaders();headers.add(“内容-编码”,"gzip“);DefaultResponseCreator drc = withSuccess( gzip( jsonData ),MediaType.APPLICATION_JSON ).headers( headers );mockServer.expect( requestTo( myService.EXTERNAL_CALL_URL )) .andExpect( method( HttpMethod.GET )).andRespond;myService.performCall();}私有静态字符串gzip(String )抛出IOException { if (str == null str.length() == 0) {返回str;} ByteArrayOutputStream out =新ByteArrayOutputStream();GZIPOutputStream gzip =新GZIPOutputStream(out);gzip.write(str.getBytes());gzip.close();String outStr = out.toString();返回outStr;}}
服务类
@Service public class MyService { public静态最终字符串EXTERNAL_CALL_URL = "";私有RestTemplate restTemplate;{ restTemplate =新RestTemplate(新HttpComponentsClientHttpRequestFactory( HttpClientBuilder.create().build();} public void (){ try { HttpHeaders requestHeaders =新HttpHeaders();requestHeaders.add(“接受-编码”,"gzip");HttpEntity< MyObject[] > requestEntity =新的HttpEntity(requestHeaders);ResponseEntity responseEntity = restTemplate.exchange( EXTERNAL_CALL_URL、HttpMethod.GET、requestEntity、MyObject[].class);MyObject[]数组= responseEntity.getBody();if (数组MyObject[] null \en19# 0) {返回null;}返回null;} catch (RestClientException e) {返回null;} public RestTemplate getRestTemplate(){返回restTemplate;}
我觉得我错过了什么。手动gzip压缩看起来相当可疑。
有人对此有什么想法吗?
提前感谢您的回答!
发布于 2016-06-12 13:15:44
当程序将gzip内容转换为string时,会折叠一些字节。因此,客户端不能解压缩它并抛出异常。一个解决方案是返回byte[]
private static byte[] gzip(String str) throws IOException {
if (str == null || str.length() == 0) {
return new byte[0];
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());//consider to use str.getBytes("UTF-8")
gzip.close();
return out.toByteArray();
}https://stackoverflow.com/questions/37722497
复制相似问题