简体   繁体   中英

Error: "java.util.zip.ZipException: Not in GZIP format" when interpreting gzip response body from API

At the moment I am attempting to make simple get calls to a mediawiki-based API, specifically liquipedia.net. Within their terms of use they require that gzip encoding be accepted, and upon printing the response headers as well as the status code, I can asses that my call is successful. However, the response body prints an unintelligible blurb of characters which I don't know how to interpret. I attempted to integrate some methods of decompressing the info, as I assumed that the information I'm receiving may still be within.GZ form, however the methods I have used usually provide errors that state that the data is not within gzip form or nothing is done with the info whatsoever.

Here's the base method which establishes the connection, and attempts to simply print the response information.

public static void GET(String address) throws IOException, InterruptedException
{
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(address))
    .header("Accept-Encoding", "Gzip")
    .header("User-Agent", "RosterBot")
    .GET()
    .build();

    HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
    HttpHeaders responseHeader = response.headers();

    
    System.out.println(responseHeader.toString());
    System.out.println(response.statusCode());



    System.out.println(decompress(response.body().getBytes()));
    
}

Here is a compression method which I used, and saw some others using

public static byte[] compress(final String str) throws IOException {
  
    System.out.println(b.toString());
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();

    return obj.toByteArray();
  }

As well as the decompression method

public static String decompress(final byte[] compressed) throws IOException {
    
    
    
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
     
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    
    return outStr.toString();
  }

Here's an example of a response body I regularly obtain

%�1� ��lM,��^aag,/J�p��ww��^d{p-���f� 4��}�����Z

As well as the response headers I receive

{ {:status=[200], accept-ranges=[bytes], age=[0], cache-control=[private, must-revalidate, max-age=0], content-disposition=[inline; filename=api-result.json], content-encoding=[gzip], content-type=[application/json; charset=utf-8], date=[Sat, 05 Jun 2021 23:56:40 GMT], referrer-policy=[no-referrer-when-downgrade], server=[nginx], vary=[Accept-Encoding, Treat-as-Untrusted, Cookie], via=[1.1 varnish (Varnish/6.5)], x-cache=[MISS], x-content-type-options=[nosniff], x-frame-options=[DENY], x-xss-protection=[1; mode=block]} }

I imagine I might be missing something obvious, but as I'm a bit new to working with API's, I would appreciate any help that can be provided!

I resolved this issue by modifying the T (type) of my HttpResponse like so

HttpResponse<InputStream> response = client.send(request, BodyHandlers.ofInputStream());

Afterwards, I parsed the data with GZIPInputStream and output the information

InputStreamReader reader = new InputStreamReader(new GZIPInputStream(response.body()));

    while (true) {
      int ch = reader.read();
      if (ch==-1) {
         break;
      }
      System.out.print((char)ch);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM