首页 > 解决方案 > 如何使用 RestTemplate 发送 Gzip 请求?

问题描述

我有以下带有大 pojo (MyRequest) 的代码,我想用 Gzip 发送它,但它无法到达接受 Gzip 请求的端点。我是否正确创建了 Gzip 请求?我需要将 pojo 作为文件发送吗?

MyRequest request = new MyRequest ();

HttpHeaders httpHeaders = HttpHeaders();
httpHeaders.add(HttpHeaders.CONTENT_ENCODING, "gzip");
httpHeaders.add(HttpHeaders.ACCEPT_ENCODING, "gzip");
httpHeaders.add(HttpHeaders.CONTENT_TYPE, "gzip");

HttpEntity<byte[]> entity = new HttpEntity<>(compress(request), headers);
ResponseEntity<MyResponse> response = restTemplate.postForEntity(url, entity, MyResponse.class);



public static Byte[] compress(byte[] body) throws IOException {
  
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {
    gzipOutputStream.write(body);
  }
  
  return baos.toByteArray();
}

请分享使用 RestTemplate 的 Gzip 编码示例,谢谢

标签: javaspring-bootgzipresttemplatespring-resttemplate

解决方案


accept-encoding: gzip, deflate, br

用于 http 客户端向服务器发出请求并期望 http 响应为:

content-encoding: gzip

对于您在做什么,请参阅此答案:https ://serverfault.com/a/56707


推荐阅读