【发布时间】:2020-10-17 07:10:49
【问题描述】:
所以基本上我试图通过尝试解压缩 gzip 来获得对 java 中的 pojo 的 gzip 编码的 json 响应。起初我从 api 调用中得到字节数组形式的响应。
CategoriesFullDetails categoriesFullDetails = new CategoriesFullDetails();
UriComponents getAllCategoriesUri = UriComponentsBuilder
.fromHttpUrl(baseUrl + MENU_CATEGORY_FULL)
.buildAndExpand(businessId);
String getAllCategoriesUrl = getAllCategoriesUri.toUriString();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Content-Type", "application/json");
requestHeaders.set("Accept-Encoding", "gzip");
HttpEntity httpEntity = new HttpEntity(requestHeaders);
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
client.setRequestFactory(requestFactory);
client.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
byte[] responseBytes = client
.exchange(getAllCategoriesUrl, HttpMethod.GET, httpEntity, byte[].class).getBody();
一旦我将 gzip 响应转换并存储为如上所示的字节数组,我想将其解压缩并将其添加到我的一个 pojo 中,即 CategoriesFullDetails。
下面是调用解压字节数组的方法。
try {
categoriesFullDetails = decompress(responseBytes);
return categoriesFullDetails;
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
return null;
}
public CategoriesFullDetails decompress(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
GZIPInputStream gis = new GZIPInputStream(in);
ObjectInputStream is = new ObjectInputStream(gis);
return (CategoriesFullDetails) is.readObject();
}
所以我在调试此解压缩方法时发现,它将数据转换为 ByteArrayInputStream,然后成功转换为 GZIPInputStream(该方法的前 2 行工作正常)。但随后在 ObjectInputStream is = new ObjectInputStream(gis); 处引发错误 说 StreamCorruptedException: invalid stream header: 7B227061
希望有人能帮助我解决这个问题,已经 3 天了,我仍然无法解决。
【问题讨论】:
-
为什么要将
GZIPInputStream转换为ObjectInputStream?来自ObjectInputStream类的javadoc:ObjectInputStream 反序列化原始数据和先前使用ObjectOutputStream 编写的对象 我认为您只需解压缩GZIPInputStream。无需转换为ObjectInputStream。 -
@Abra 你能告诉我如何解压缩 GZIPInputStream,这对我真的很有帮助,顺便说一句,如果我将它转换为 ObjectInputStream,那么我将能够将它添加到我的 pojo就像下一行一样。
-
但如果它不是由
ObjectOutputStream制作的,你就不能这样做。
标签: java json spring spring-boot gzip