package com.pp;
/*功能:返回一个网址的网页源代码*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class URLTest{
public static String getUrl(String strUrl) {
StringBuffer codeBuffer = null;
BufferedReader in = null;
try {
URLConnection uc = new URL(strUrl).openConnection();
uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
// 读取url流内容
in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "gb2312"));
codeBuffer = new StringBuffer();
String tempCode = "";
// 把buffer内的值取出来保存到code中
while ((tempCode = in.readLine()) != null) {
codeBuffer.append(tempCode).append("/n");
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return codeBuffer.toString();
}
public static void main(String[] args) {
String url="www.baidu.com"; //要采集网页的网址
String s = URLTest.getUrl(url);//s是采集到的网址的网页源代码
System.out.println(s);
}
}
本文介绍了一个简单的Java程序,该程序通过发送HTTP请求来抓取并返回指定URL的网页源代码。程序使用了标准的Java网络和IO库,能够帮助理解基本的网络爬虫实现。
3267

被折叠的 条评论
为什么被折叠?



