使用httpClient保存网页至本地
2017-03-03 16:09
337 查看
package com.gewb; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; public class Spider { private static HttpClient httpClient = new HttpClient(); /** * @param path * 目标网页的链接 * @return 返回布尔值,表示是否正常下载目标页面 * @throws Exception * 读取网页流或写入本地文件流的IO异常 */ public static boolean downloadPage(String path) throws Exception { // 定义输入输出流 InputStream input = null; OutputStream output = null; // 得到 post 方法 GetMethod getMethod = new GetMethod(path); // 执行,返回状态码 int statusCode = httpClient.executeMethod(getMethod); // 针对状态码进行处理 // 简单起见,只处理返回值为 200 的状态码 if (statusCode == HttpStatus.SC_OK) { input = getMethod.getResponseBodyAsStream(); // 通过对URL的得到文件名 String filename = path.substring(path.lastIndexOf('/') + 1) + ".html"; // 获得文件输出流 output = new FileOutputStream(filename); // 输出到文件 int len = 0; byte[] b = new byte[1024]; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } // 关闭输入流 if (input != null) { input.close(); } // 关闭输出流 if (output != null) { output.close(); } System.out.println("成功"); return true; } System.out.println("失败"); return false; } public static void main(String[] args) { try { // 抓取百度首页,输出 Spider.downloadPage("http://www.baidu.com"); } catch (Exception e) { e.printStackTrace(); } } }
相关文章推荐
- 【知识积累】使用Httpclient实现网页的爬取并保存至本地
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件 分类: C_OHTERS 2014-05-19 15:07 1108人阅读 评论(0) 收藏
- 【搜索引擎Jediael开发笔记2】使用HttpClient下载网页至本地文件
- 使用365Key-天天网摘来保存浏览过的网页
- [转]使用URLConnection下载文件或图片并保存到本地
- 使用java将网页保存为mht格式
- 快速浏览Silverlight3 Beta:使用SaveFileDialog保存到本地文件
- 禁止别人使用"另存为"保存你的网页
- 使用java将网页保存为mht格式(1)
- 使用httpclient下载需要登录的网页续
- 如何利用asp保存远程网页中的图片到本地来!
- 如何利用asp保存远程网页中的图片到本地来!
- 快速浏览Silverlight3 Beta:使用SaveFileDialog保存到本地文件
- 用ASP简单封装了几个函数,使用ServerXMLHTTP把网络上的文件保存到本地服务器.
- 使用XMLHttp和ADODB.Stream取得远程文件并保存到本地
- 保存网页图片到本地硬盘!!