快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

获取网页源代码java 获取网页源代码的函数

Java访问指定URL并获取网页源代码

1.编写useSourceViewer 类的基本框架,该类仅包括无返回值的main ()方法,该方法从参数中获取URL,通过输入缓冲和输出缓冲将该URL 原码输出。

成都创新互联长期为数千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为红桥企业提供专业的网站设计制作、成都网站建设红桥网站改版等技术服务。拥有10年丰富建站经验和众多成功案例,为您定制开发。

2.编写useSourceViewer 类,代码如下:

import java.net.*;

import java.io.*;

public class useSourceViewer

{

public static void main (String[] args)

{

if (args.length 0)

{

try

{

//读入URL

URL u = new URL(args[0]);

InputStream in = u.openStream( );

// 为增加性能存储输入流

in = new BufferedInputStream(in);

// 将输入流连接到阅读器

Reader r = new InputStreamReader(in);

int c;

while ((c = r.read( )) != -1)

{

System.out.print((char) c);

}

Object o = u.getContent( );

System.out.println("I got a " + o.getClass().getName( ));

}

catch (MalformedURLException e)

{

System.err.println(args[0] + " is not a parseable URL");

}

catch (IOException e)

{

System.err.println(e);

}

} // end if

} // end main

} // end SourceViewer}

java程序读取一个url页面的源代码

传入一个url,返回源代码; public static String getHTML(String url){// 获取指定URL的网页,返回网页内容的字符串,然后将此字符串存到文件即可 try { URL newUrl = new URL(url); URLConnection connect = newUrl.openConnection(); connect.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); DataInputStream dis = new DataInputStream(connect.getInputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(dis,"UTF-8")); String html = ""; String readLine = null; while((readLine = in.readLine()) != null) { html = html + readLine; } in.close(); return html; }catch (MalformedURLException me){ System.out.println("MalformedURLException" + me); }catch (IOException ioe){ System.out.println("ioeException" + ioe); } return null; }

java中如何根据一个网址获得该网页的源代码?

package test;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class HttpTest {

private String u;

private String encoding;

public static void main(String[] args) throws Exception {

HttpTest client = new HttpTest("", "UTF-8");

client.run();

}

public HttpTest(String u, String encoding) {

this.u = u;

this.encoding = encoding;

}

public void run() throws Exception {

URL url = new URL(u);// 根据链接(字符串格式),生成一个URL对象

HttpURLConnection urlConnection = (HttpURLConnection) url

.openConnection();// 打开URL

BufferedReader reader = new BufferedReader(new InputStreamReader(

urlConnection.getInputStream(), encoding));// 得到输入流,即获得了网页的内容

String line; // 读取输入流的数据,并显示

while ((line = reader.readLine()) != null) {

System.out.println(line);

}

}

}

根据具体问题类型,进行步骤拆解/原因原理分析/内容拓展等。

具体步骤如下:/导致这种情况的原因主要是……


新闻名称:获取网页源代码java 获取网页源代码的函数
网页地址:http://6mz.cn/article/dosodpd.html

其他资讯