在将JSON提交到服务器之前,有没有办法压缩它?我曾尝试使用Pako来GZIP JSON,但出于某种原因,服务器代码一直告诉我它不是GZIP字符串
我真的不关心它是什么类型的压缩,只要它可以在Ionic2客户端压缩并在java中解压缩(膨胀)
以下是我的尝试:
let body = JSON.stringify(data);
let gzippedBody = Pako.gzip(body);
let headers = new Headers({ "Content-Encoding" : "gzip"});
headers.append('Content-Type', 'application/json; charset=x-user-defined-binary');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, gzippedBody, options);
在服务器端:
@RequestMapping(value = "/save",method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public ValidatorResult saveCancelledSessionNotes(@RequestBody String json ) throws JsonParseException, JsonMappingException, IOException
{
json = decompress(json.getBytes());
}
public static String decompress(final byte[] compressed) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(bis);
byte[] bytes = IOUtils.toByteArray(gis);
return new String(bytes, "UTF-8");
}
服务器上的Stacktrace:
java.util.zip.ZipException: Not in GZIP format
at java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:165)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:79)
at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:91)