1.1 深入理解URL
在理解URL之前,首先要理解URI的概念。什么是URI?web上的每种可用的资源,如HTML文档、图像、视频片段、程序都能都是由一个通用资源标志符进行定位的。URI通常由三部分组成:1、访问资源的命名机制;2、存放资源的主机名;3、资源自身的名称,由路径表示。URL是URI的一个子集,URL是internet上描述信息资源的字符串,主要用在各种www客户程序和服务器程序上。
1.1.2
通过指定的URL抓取网页的内容
为了便于应用程序的开发,实际开发时常使用Apachede HTTP客户端开源项目——HTTPClient。在项目中映入HttpClient.java包,就可以模拟IE来获取网页的内容。可以用get和post两种方式访问web资源。
HttpClient的功能如下:
1、实现了所有的HTTP方法(GET,POST,PUT,HEAD)
2、支持自动转向
3、支持Http协议
4、支持代理服务器等
1.1.3 java网页抓取实例
代码如下:
package com.crawler;
import java.io.*;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
public class RetrivePage {
/**
* @param args
*/
private static HttpClient httpClient = new HttpClient();
//设置代理服务器
static{
//设置代理服务器的IP地址和端口
httpClient.getHostConfiguration().setProxy("172.17.18.84", 8080);
}
public static boolean downloadPage(String path)throws HttpException,
IOException{
InputStream input = null;
OutputStream output = null;
PostMethod postMethod = new PostMethod(path);
NameValuePair[]postData = new NameValuePair[2];
postData[0] = new NameValuePair("name", "lietu");
postData[1] = new NameValuePair("password", "12345");
postMethod.addParameters(postData);
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == HttpStatus.SC_OK)
{
input = postMethod.getResponseBodyAsStream();
String filename = path.substring(path.lastIndexOf('/')+1);
output = new FileOutputStream(filename);
int tempByte = -1;
while((tempByte=input.read())>0)
{
output.write(tempByte);
}
if(input !=null)
{
input.close();
}
if(output != null)
{
output.close();
}
return true;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
RetrivePage.downloadPage("http://www.lietu.com/");
}catch(HttpException e)
{
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
HttpClient访问Web资源的时候,设计HTTP状态码。如下面这条语句:
int statusCode=httpClient.execyteMethod(getMethod);
HTTP状态码表示HTTP协议所返回的相应的状态。比如客户端想服务器发送请求,如果成功的获得请求的资源,泽返回的转台吗是200,表示成功。如果 请求的资源不存在,则通常返回404错误。