我正在尝试将HTTP响应的HTTP正文转换为明文。我已经将此响应的字节数组转换为ByteArrayInputStream。然后,我将其转换为GZIPInputStream。现在,我希望读取GZIPInputStream并将最终解压缩的HTTP响应体存储为纯文本字符串。
这段代码将最终解压缩的内容存储在OutputStream中,但我想将内容存储为字符串:
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);
}发布于 2010-09-02 21:17:07
要解码InputStream中的字节,可以使用InputStreamReader。然后,BufferedReader将允许您逐行读取流。
您的代码将如下所示:
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);
}发布于 2010-09-02 21:17:03
您应该以InputStream而不是byte[]的形式获得响应。然后,您可以使用GZIPInputStream解压缩它,并使用InputStreamReader将其作为字符数据读取,最后使用StringWriter将其作为字符数据写入String。
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();
}
// ...另请参阅:
如果您的最终目的是将响应解析为HTML语言,那么我强烈建议您只使用像Jsoup这样的HTML解析器。然后它就像下面这样简单:
String html = Jsoup.connect("http://google.com").get().html();发布于 2017-01-24 03:26:48
使用try-with-resources习惯用法(它会自动关闭try(...)中打开的任何资源)从代码块中退出时),以使代码更清晰。
使用Apache IOUtils将inputStream转换为使用默认CharSet的字符串。
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);
}
}https://stackoverflow.com/questions/3627401
复制相似问题