目前我可以按如下方式检索文本页面
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://google.com");
try {
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
假设get是针对二进制文件的。如何将其正确保存到磁盘?
答案 0 :(得分:7)
只是不要通过Reader
- 阅读InputStream
中的数据并写信给OutputStream
。
// Using Guava (guava-libraries.googlecode.com)
InputStream data = response.getEntity().getContent();
try {
OutputStream output = new FileOutputStream(filename);
try {
ByteStreams.copy(data, output);
} finally {
Closeables.closeQuietly(output);
}
} finally {
}