java 获取网页源码

知识创造技术 技术改变世界

------ Oracle中文开发者社区 ------

二维码 二维码 二维码 二维码 二维码 二维码
如果你想要学习编程,关注本博客,持续获得技术支持,持续获得技术咨询

java开发·企业官方账号 Oracle中国官方账号 Java中国管理部 全网粉丝30万+ 华为云享专家 阿里专家博主 CSDN内容合伙人 CSDN原力计划作者 51CTO专家博主 CSDN博客V账号 毕业于四川大学新闻与文学学院 精通java,Python,HTML,掌握了PHP,C语言,C++,C#,JavaScript,Visual Basic等二十余种编程语言的技巧,会分享一些编程心得、面试技巧和编程方法。


其他链接

主页 官网 社区 论坛


如何使用Java获取网页源代码,说到这里我们不得不学习一下java中 URL处理
URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址。

介绍一下Java是如处理URL的。URL可以分为如下几个部分。

protocol://host:port/path?query#fragment

protocol(协议)可以是 HTTP、HTTPS、FTP 和 File,port 为端口号,path为文件路径及文件名。

HTTP 协议的 URL 实例如下:

http://www.runoob.com/index.html?language=cn#j2se

URL 解析:

  • 协议为(protocol):http
  • 主机为(host:port):www.runoob.com
  • 端口号为(port): 80 ,以上URL实例并未指定端口,因为 HTTP 协议默认的端口号为 80。
  • 文件路径为(path):/index.html
  • 请求参数(query):language=cn
  • 定位位置(fragment):j2se,定位到网页中 id 属性为 j2se 的 HTML 元素位置 。

URL 类方法

在java.net包中定义了URL类,该类用来处理有关URL的内容。对于URL类的创建和使用,下面分别进行介绍。

java.net.URL提供了丰富的URL构建方式,并可以通过java.net.URL来获取资源。

序号方法描述
1public URL(String protocol, String host, int port, String file) throws MalformedURLException.通过给定的参数(协议、主机名、端口号、文件名)创建URL。
2public URL(String protocol, String host, String file) throws MalformedURLException使用指定的协议、主机名、文件名创建URL,端口使用协议的默认端口。
3public URL(String url) throws MalformedURLException通过给定的URL字符串创建URL
4public URL(URL context, String url) throws MalformedURLException使用基地址和相对URL创建

URL类中包含了很多方法用于访问URL的各个部分,具体方法及描述如下:

序号方法描述
1public String getPath()返回URL路径部分。
2public String getQuery()返回URL查询部分。
3public String getAuthority()获取此 URL 的授权部分。
4public int getPort()返回URL端口部分
5public int getDefaultPort()返回协议的默认端口号。
6public String getProtocol()返回URL的协议
7public String getHost()返回URL的主机
8public String getFile()返回URL文件名部分
9public String getRef()获取此 URL 的锚点(也称为"引用")。
10public URLConnection openConnection() throws IOException打开一个URL连接,并运行客户端访问资源。

实例

以上实例演示了使用java.net的URL类获取URL的各个部分参数:

URLDemo.java

import java.net.*;
import java.io.*;
 
public class URLDemo
{
   public static void main(String [] args)
   {
      try
      {
         URL url = new URL("http://www.runoob.com/index.html?language=cn#j2se");
         System.out.println("URL 为:" + url.toString());
         System.out.println("协议为:" + url.getProtocol());
         System.out.println("验证信息:" + url.getAuthority());
         System.out.println("文件名及请求参数:" + url.getFile());
         System.out.println("主机名:" + url.getHost());
         System.out.println("路径:" + url.getPath());
         System.out.println("端口:" + url.getPort());
         System.out.println("默认端口:" + url.getDefaultPort());
         System.out.println("请求参数:" + url.getQuery());
         System.out.println("定位位置:" + url.getRef());
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

以上实例编译运行结果如下:
URL 为:http://www.runoob.com/index.html?language=cn#j2se
协议为:http
验证信息:www.runoob.com
文件名及请求参数:/index.html?language=cn
主机名:www.runoob.com
路径:/index.html
端口:-1
默认端口:80
请求参数:language=cn
定位位置:j2se

URLConnections 类方法

openConnection() 返回一个 java.net.URLConnection。

例如:

如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。

如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。

等等…

URLConnection 方法列表如下:

序号 方法描述
1 Object getContent()
检索URL链接内容
2 Object getContent(Class[] classes)
检索URL链接内容
3 String getContentEncoding()
返回头部 content-encoding 字段值。
4 int getContentLength()
返回头部 content-length字段值
5 String getContentType()
返回头部 content-type 字段值
6 int getLastModified()
返回头部 last-modified 字段值。
7 long getExpiration()
返回头部 expires 字段值。
8 long getIfModifiedSince()
返回对象的 ifModifiedSince 字段值。
9 public void setDoInput(boolean input)
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true。
10 public void setDoOutput(boolean output)
URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false。
11 public InputStream getInputStream() throws IOException
返回URL的输入流,用于读取资源
12 public OutputStream getOutputStream() throws IOException
返回URL的输出流, 用于写入资源。
13
public URL getURL()
返回 URLConnection 对象连接的URL

接下我们开始写java代码,获取网页源码:

package com;
/**
 * 获取网页源码
 * yongxinYang   2019-11-21  20:00
 */
import java.io.*;
import java.net.*;
 
public class  ExcepTest  {
 
    public static String getHtmlContent(URL url, String encode) {
        StringBuffer contentBuffer = new StringBuffer();
 
        int responseCode = -1;
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
            /*
            * 此处的urlConnection对象实际上是根据URL的
            *  请求协议(此处是http)生成的URLConnection类
            *  的子类HttpURLConnection,故此处最好将其转化
            * 为HttpURLConnection类型的对象,以便用到
            *  HttpURLConnection更多的API
            * */
            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");// IE代理进行下载
            con.setConnectTimeout(60000);
            con.setReadTimeout(60000);
            // 获得网页返回信息码
            responseCode = con.getResponseCode();
            if (responseCode == -1) {
                System.out.println(url.toString() + " : connection is failure...");
                con.disconnect();
                return null;
            }
            if (responseCode >= 400) // 请求失败
            {
                System.out.println("请求失败:get response code: " + responseCode);
                con.disconnect();
                return null;
            }
 
            InputStream inStr = con.getInputStream();
            InputStreamReader istreamReader = new InputStreamReader(inStr, encode);
            BufferedReader buffStr = new BufferedReader(istreamReader);
 
            String str = null;
            while ((str = buffStr.readLine()) != null)
                contentBuffer.append(str);
            inStr.close();
        } catch (IOException e) {
            e.printStackTrace();
            contentBuffer = null;
            System.out.println("error: " + url.toString());
        } finally {
            con.disconnect();
        }
        return contentBuffer.toString();
    }
 
    public static String getHtmlContent(String url, String encode) {
 
        try {
            URL rUrl = new URL(url);
            return getHtmlContent(rUrl, encode);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    public static void main(String argsp[]){
        //程序入口,传入网页链接,和网页编码
        System.out.println(getHtmlContent("https://movie.douban.com/subject/27119724/","utf-8")) ;
    }
 
}

本文到此就结束了,后面我会写一下如何在网页获取我们需要的数据。


------- THE END -------
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code Writers

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值