我正在使用Spring-MVC rest API,我们的一项服务必须允许设备客户端根据需要下载一些数据:json或deflated json。
但是我们的服务公开的数据来自第三方组件,即字节数组,对此我们一无所知(请问此字节数组是表示json还是缩小的json,不了解数据模型)
只需一点点代码就可以理解:
@GetMapping(value = "/data/{dataType}")
public ResponseEntity<byte[]> test(
@PathVariable String dataType,
@RequestHeader("Accept-Encoding") String acceptEncoding){
// get data from third-party
byte[] blob = thirdPartyComponent.getData(dataType);
boolean isBlobDeflated = thirdPartyComponent.isDataDeflated(dataType);
// compress/uncompress on demand
byte[] data;
String contentEncoding = "deflate".equals(acceptEncoding) ? "deflate" : "identity";
if ("deflate".equals(contentEncoding)){
// get compressed data
if (isBlobDeflated){
data = blob;
} else {
data = deflate(blob);
}
} else {
// get uncompress data
if (isBlobDeflated){
data = inflate(blob);
} else {
data = blob;
}
}
// set response header
HttpHeaders header = new HttpHeaders();
header.set("Content-Type" , "application/json");
header.set("Content-Encoding", contentEncoding);
header.setContentLength(data.length); // must be data or inflated data length ?
// find a way to tell spring-MVC to perform no conversion nor compression,
// and return the data as it
return new ResponseEntity<>(data, header, HttpStatus.OK);
}
但是我不确定此示例代码是否可以工作。 我猜想有些配置要求Spring-MVC不执行任何转换或压缩。我对吗 ? 并且“ content-length”标头必须反映膨胀的数据长度?
如何做得很好? 谢谢