Pergunta

Primeiro de tudo, sinto muito se minha terminologia é um pouco amadora, tente me suportar;)

Estou tentando converter o corpo de uma resposta HTTP em texto simples. Peguei a matriz de bytes dessa resposta e a converti em um bytearrayInputStream. Em seguida, converti isso em um gzipinputStream. Agora, quero ler o GzipinputStream e armazenar o corpo final de resposta HTTP descompactado como uma string de texto simples.

Este código armazenará o conteúdo final descompactado em uma forma de saída, mas quero armazenar o conteúdo como uma string:

public static int sChunk = 8192;
ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
byte[] buffer = new byte[sChunk];
int length;
while ((length = gzis.read(buffer, 0, sChunk)) != -1) {
        out.write(buffer, 0, length);
}
Foi útil?

Solução

Para decodificar bytes de um inputStream, você pode usar um InputStreamReader. Então uma BufferredReader Permitirá que você leia sua linha por linha.

Seu código será:

ByteArrayInputStream bais = new ByteArrayInputStream(responseBytes);
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);

String readed;
while ((readed = in.readLine()) != null) {
    System.out.println(readed);
}

Outras dicas

Você prefere ter obtido a resposta como um InputStream em vez de como byte[]. Então você pode ungzip usando GZIPInputStream e leia -o como dados de caracteres usando InputStreamReader e finalmente escreva como dados de caracteres em um String usando StringWriter.

String body = null;
String charset = "UTF-8"; // You should determine it based on response header.

try (
    InputStream gzippedResponse = response.getInputStream();
    InputStream ungzippedResponse = new GZIPInputStream(gzippedResponse);
    Reader reader = new InputStreamReader(ungzippedResponse, charset);
    Writer writer = new StringWriter();
) {
    char[] buffer = new char[10240];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        writer.write(buffer, 0, length);
    }
    body = writer.toString();
}

// ...

Veja também:


Se sua intenção final é analisar a resposta como HTML, recomendo fortemente usar um analisador HTML para isso como JSUP. É então tão fácil quanto:

String html = Jsoup.connect("http://google.com").get().html();

Use o idioma Try-With-RESOURCES (que fecha automaticamente quaisquer recursos abertos em tentativa (...) na saída do bloco) para tornar o código mais limpo.

Use o Apache ioutils para converter o InputStream para string usando o charset padrão.

import org.apache.commons.io.IOUtils;
public static String gzipFileToString(File file) throws IOException {
    try(GZIPInputStream gzipIn = new GZIPInputStream(new FileInputStream(file))) {
        return IOUtils.toString(gzipIn);
    }
}

Use o Apache Commons para converter GzipinputStream em Bytearray.

import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.IOUtils;

public static byte[] decompressContent(byte[] pByteArray) throws IOException {
        GZIPInputStream gzipIn = null;
        try {
            gzipIn = new GZIPInputStream(new ByteArrayInputStream(pByteArray));
            return IOUtils.toByteArray(gzipIn);
        } finally {
            if (gzipIn != null) {
                gzipIn.close();
            }
        }

Para converter o conteúdo não compactado de matriz de bytes em string, faça algo assim:

String uncompressedContent = new String(decompressContent(inputStream));

Você pode usar o StringWriter para escrever para string

import java.io.*;
import java.util.zip.*;

public class Ex1 {

    public static void main(String[] args) throws Exception{
        String str ;

        H h1 = new H();
        h1.setHcfId("PH12345658");
        h1.setHcfName("PANA HEALTH ACRE FACILITY");

        str = h1.toString();
        System.out.println(str);

        if (str == null || str.length() == 0) {
            return ;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        out.close();

        String s =  out.toString() ;
        System.out.println( s );
        byte[] ba = out.toByteArray();
        System.out.println( "---------------BREAK-------------" );

        ByteArrayInputStream in = new ByteArrayInputStream(ba);
        GZIPInputStream gzis = new GZIPInputStream(in);
        InputStreamReader reader = new InputStreamReader(gzis);
        BufferedReader pr = new BufferedReader(reader);

        String readed;
        while ((readed = pr.readLine()) != null) {
            System.out.println(readed);
        }

        //Close all the streams
    }

}

você também pode fazer

try (GZIPInputStream gzipIn = new GZIPInputStream(new ByteArrayInputStream(pByteArray)))
{
....
}

Autoclosable é uma coisa boahttps://docs.oracle.com/javase/tutorial/essential/exceptions/tryresourceclose.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top