1

I've been having some trouble with recieving a compressed Gzip file in java. When I run the following code to recieve it:

        HttpClient httpClient = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://peoplegeneratorapi.live/api/person/100"))
                .method("GET", HttpRequest.BodyPublishers.noBody())
                .header("Accept-Encoding", "gzip")
                .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());

I get:

�g�x�<$�EV��h?��_%��i�yS?���IY�gYQ�����O�&���q���n|�ܖ   ���rw��^?�U��G��iR.qqi���wE���A�]$q���}�~�L��6-�1^���p�N��m:}q�g/�3���p��R���b�OgE]�� �A:{�_ �N�YR�������8��E&Ey�D�O�y>+V?s��f�(·���>��O|I!^�!��(�ᾃ�g�Qp�w�"O�o��Y%"F%�[k�7Y\�?�/���8��_������^h�g��y�Z����׸�� ɟ�b�س�̒��"���%\�ކ�K8���mDyDԁTD-�J��«�M�jї^O�����Q��>�/o�k>R_�O�X]ܲ  �ã����¤��9X�n��[�J5�.�p��v��w����E�F��<n@�h>'�|�`�uQ~�02x=.9R��BGDpI    �_� ���W|��X�ݧ�������x��ȋ�$��������d]%wр�!�]���s)�U���ݛ_7�7�G�0^=��0�L��5]���a-�Q��$���I�>���H��q��L���?콙'ә��~�*��O3M��'����2� �] \ޫ�?K� �H���X�5�w�ނ���ƃb0���cj���h��<.��d0��A�h\Cs@䁨�7�60�\

So far, I've been able to use this to decompress it:

private static String decompressGzip(byte[] compressedData) {
        try (GZIPInputStream gis = new GZIPInputStream(
                new ByteArrayInputStream(compressedData))) {
            return new String(gis.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            return null;
        }
    }

But I can't help but think there must be some better way to do this without having to manually decrypt the byte array. Does anybody have any insight into this?

1 Answers1

0

BodyHandlers.ofInputStream() will give you an InputStream rather than a String:

HttpResponse<InputStream> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofInputStream());
String body = new String(new GZIPInputStream(response.body()).readAllBytes());

(Assuming this is inside a block that will do the exception handling.)

Siguza
  • 21,155
  • 6
  • 52
  • 89