尝试阅读“http://www.mtv.de/news_sitemap.xml.gz”,但数据似乎没有得到很好的解码:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.mtv.de/news_sitemap.xml.gz")
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
catch(IOException e)
{
}
文件有什么问题,或者我应该安装/配置的东西?
答案 0 :(得分:0)
您正在下载的文件是压缩文件。命令:
的System.out.println(response.body()字符串());
无法解压缩文件并打印出文件内容。您应该首先提取文件,然后打印出提取的文件。我们试试下面的例子:
@Test
public void testDownloadFile() throws IOException {
Request request = new Request.Builder()
.url("http://www.mtv.de/news_sitemap.xml.gz")
.build();
try {
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
ByteArrayInputStream bais = new ByteArrayInputStream(response.body().bytes());
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);
}
} catch (IOException e) {
}
}