response中Content-Encoding为gzip的数据读取解压

Content-Encoding为gzip时,数据的读取

import org.springframework.core.io.Resource;

RestTemplate RT = RestUtil.getRestTemplate();
ResponseEntity<Resource> response = RT.postForEntity(url, entity, Resource.class);
HttpHeaders header = response.getHeaders();
List<String> contentEncodingList = header.get("Content-Encoding");
InputStream is = response.getBody().getInputStream();
if ((CollUtil.isNotEmpty(contentEncodingList) && StrUtil.contains(contentEncodingList.get(0).toLowerCase(), "gzip"))) {
  byte[] b = IOUtils.toByteArray(is);
  ByteArrayInputStream bais = new ByteArrayInputStream(b);
  GZIPInputStream gzis = new GZIPInputStream(bais);
  InputStreamReader reader = new InputStreamReader(gzis);
  BufferedReader in = new BufferedReader(reader);
  String temp;
  while ((temp = in.readLine()) != null) {
    sb.append(temp);
    sb.append("\r\n");
  }
} else {
  // 构造一个字符流缓存
  BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  String temp;
  while ((temp = br.readLine()) != null) {
    sb.append(temp);
    sb.append("\r\n");
  }
}
is.close();

站在巨人肩膀上摘苹果

https://blog.csdn.net/wley_233/article/details/115201733

# Java  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×