java学习-GET方式抓取网页(UrlConnection和HttpClient) 参考

来源:互联网 发布:淘宝网男士加厚衬衣 编辑:程序博客网 时间:2024/06/05 06:02

URL:http://www.cnblogs.com/gne-hwz/p/6952312.html


抓取网页其实就是模拟客户端(PC端,手机端。。。)发送请求,获得响应数据documentation,解析对应数据的过程。---自己理解,错误请告知

一般常用请求方式有GET,POST,HEAD三种

GET请求的数据是作为url的一部分,对于GET请求来说,附带数据长度有限制,数据安全性低

POST请求,数据作为标准数据传输给服务器,数据长度没有限制,数据通过加密传输,安全性高

HEAD类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头

闲话少说。

通过GET请求获取网页

UrlConnection下载网页通过InputStream读取数据,通过FileOutPutStream将数据写入文件

复制代码
public class DownloadHtml {     /**     * 方法说明:用于下载HTML页面     *@param SrcPath  下载目标页面的URL     *@param filePath 下载得到的HTML页面存放本地目录     *@param fileName  下载页面的名字     */    public static void downloadHtmlByNet(String SrcPath,String filePath,String fileName){        try{            URL url = new URL(SrcPath);            URLConnection conn = url.openConnection();            //设置超时间为3秒            conn.setConnectTimeout(3*1000);            //防止屏蔽程序抓取而返回403错误            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");            //输出流            InputStream str = conn.getInputStream();            //控制流的大小为1k            byte[] bs = new byte[1024];            //读取到的长度            int len = 0;            //是否需要创建文件夹            File saveDir = new File(filePath);              if(!saveDir.exists()){                  saveDir.mkdir();              }              File file = new File(saveDir+File.separator+fileName);               //实例输出一个对象            FileOutputStream out = new FileOutputStream(file);            //循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read();            while ((len = str.read(bs)) != -1) {                //将对象写入到对应的文件中                out.write(bs, 0, len);               }            //刷新流            out.flush();            //关闭流            out.close();            str.close();                    System.out.println("下载成功");        }catch (Exception e) {            e.printStackTrace();        }    }    //测试    public static void main(String[] args) {         //下载网页
    url是要下载的指定网页,filepath存放文件的目录如
d:/resource/html/ ,filename指文件名如"下载的网页.html"

downloadHtmlByNet(url,filepath,filename); }}
复制代码

HttpClient是Apache Jakarta Common 下的子项目。提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包

复制代码
public static void downloadHtmlByNet(String SrcPath,String filePath,String fileName){        DefaultHttpClient httpClient=new DefaultHttpClient();//初始化httpclient        BasicHttpParams httpParams=new BasicHttpParams();//初始化参数
//模拟浏览器访问防止屏蔽程序抓取而返回403错误
user_agent="Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
     

user_agent="Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"
        httpParams.setParameter("http.useragent", user_agent);        httpClient.setParams(httpParams);        try {            HttpGet httpGet=new HttpGet(SrcPath);            HttpContext httpContext=new BasicHttpContext();            HttpResponse httpResponse=httpClient.execute(httpGet,httpContext);            HttpEntity entity=httpResponse.getEntity();            if(entity!=null){                writeToFile(entity,filePath,fileName);//将entity内容输出到文件                          }        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }         finally {                httpClient.getConnectionManager().shutdown();            }    }
复制代码
复制代码
private static void writeToFile(HttpEntity entity, String filepath, String filename) {        //输出流        try{        InputStream str = entity.getContent();        //控制流的大小为1k        byte[] bs = new byte[1024];        //读取到的长度        int len = 0;        //是否需要创建文件夹        File saveDir = new File(filePath);          if(!saveDir.exists())           {            saveDir.mkdir();             }        File file = new File(saveDir+File.separator+fileName);      //实例输出一个对象        FileOutputStream out = new FileOutputStream(file);        //循环判断,如果读取的个数b为空了,则is.read()方法返回-1,具体请参考InputStream的read();        while ((len = str.read(bs)) != -1) {            //将对象写入到对应的文件中            out.write(bs, 0, len);           }        //刷新流        out.flush();        //关闭流        out.close();        str.close();                System.out.println("下载成功");        }        catch(Exception e){            e.printStackTrace();        }    }
复制代码