• Java如何读取和下载网页?


    在Java编程中,如何读取和下载网页?

    以下示例显示如何使用net.URL类的URL()构造函数来读取和下载网页。

    package com.yiibai;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.net.URL;
    
    public class DownloadingWebpage {
        public static void main(String[] args) throws Exception {
            URL url = new URL("http://www.yiibai.com");
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            BufferedWriter writer = new BufferedWriter(new FileWriter("save2yiibai-index.html"));
            String line;
    
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                writer.write(line);
                writer.newLine();
            }
            reader.close();
            writer.close();
        }
    }
    
    Java

    上述代码示例将产生以下结果(输出易百教程的首页页面源代码,并保存到save2yiibai-index.html文件中) -

    <!--
    输出易百教程的首页页面源代码
    -->
    <!DOCTYPE HTML>
    <html>
    <head><!--
    
    -->
    <!DOCTYPE HTML>
    <html>
    <head>
    ... ... 省略
    
    Shell

    示例-2

    Java读取和下载网页的另一个示例:

    package com.yiibai;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    public class DownloadingWebpage2 {
        public static void main(String[] args) {
            URL url;
            InputStream is = null;
            BufferedReader br;
            String line;
            try {
                url = new URL("http://www.yiibai.com/javaexamples/date_time_month.html");
                is = url.openStream(); // throws an IOException
                br = new BufferedReader(new InputStreamReader(is));
    
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (MalformedURLException mue) {
                mue.printStackTrace();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException ioe) {
                }
            }
        }
    }
    
    Java

    上述代码示例将产生以下结果(输出页面源代码) -

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    ...... 省略
  • 相关阅读:
    eclipse快捷键
    NetBeans无法使用svn相关功能
    sqlplus执行startup出现ORA-00119,ORA-00132错误
    Oracle中对number类型数据to_char()出现各位少0,或者值为###的处理
    服务器启动报mybatis配置错误
    Java Thread interrupt
    nginx backend 健康检查
    SSH 安全建议
    ARP
    Postgresql 锁查看
  • 原文地址:https://www.cnblogs.com/borter/p/9617173.html
Copyright © 2020-2023  润新知