上一次写了一个很简单的爬虫,这一次将在上一次的基础上进行优化,上次访问Web资源的时候,设计到了HTTP状态码,只处理了为200的请求,接下来了解下HTTP状态码
HTTP状态码:
HTTP状态码的作用是:Web服务器用来告诉客户端,发生了什么事。
状态码位于HTTP Response 的第一行中,会返回一个”三位数字的状态码“和一个“状态消息”。 ”三位数字的状态码“便于程序进行处理, “状态消息”更便于人理解。 我们可以利用谷歌浏览器查看HTTP的请求头,里面就包含了状态码。
状态码分类
HTTP状态码被分为五大类, 目前我们使用的HTTP协议版本是1.1, 支持以下的状态码。随着协议的发展,HTTP规范中会定义更多的状态码。
小技巧: 假如你看到一个状态码518, 你并不知道具体518是什么意思。 这时候你只要知道518是属于(5XX,服务器错误就可以了)
已定义范围 | 分类 | |
1XX | 100-101 | 信息提示 |
2XX | 200-206 | 成功 |
3XX | 300-305 | 重定向 |
4XX | 400-415 | 客户端错误 |
5XX | 500-505 | 服务器错误 |
当返回值状态码为3XX时,表示进行重定向,那么接下来可以把上次的代码进行改写以下了。
public class UrlReptile {
private static HttpClient httpClient = new HttpClient(); // 创建一个代理服务器
/*static {
// 设置代理服务器的IP和端口
httpClient.getHostConfiguration().setProxy("172.16.1.32",8080);
}*/
public static boolean downLoadPage(String path) throws IOException {
// 创建输入输出流
InputStream inputStream = null;
OutputStream outputStream = null;
/*// 得到post方法
PostMethod postMethod = new PostMethod(path);*/
//得到get方法
GetMethod getMethod=new GetMethod(path);
// 设置post方法的参数
/* NameValuePair[] postData = new NameValuePair[2];
postData[0] = new NameValuePair("name", "baidu");
postData[1] = new NameValuePair("password", "******");
postMethod.addParameters(postData);*/
try {
// 执行返回状态码
int statusCode = httpClient.executeMethod(getMethod);
//处理状态为3XX的
if(statusCode==HttpStatus.SC_MOVED_TEMPORARILY||
statusCode==HttpStatus.SC_SEE_OTHER||
statusCode==HttpStatus.SC_TEMPORARY_REDIRECT){
//读取新的URL地址
Header header=getMethod.getRequestHeader("location");
if(header!=null){
String newUrl=header.getValue();
if(newUrl==null||newUrl.equals("")){
newUrl="/";
//重定向处理
GetMethod method=new GetMethod(newUrl);
}
}
}
// 处理状态吗
if (statusCode == HttpStatus.SC_OK) { // 200表示成功
// 得到输入流
inputStream = getMethod.getResponseBodyAsStream();
// 得到文件名
String fileName = path.substring(path.lastIndexOf('/')+1)+ ".html";
// 得到输出流
outputStream = new FileOutputStream(fileName);
// 输出到文件
int tByte = -1;
while ((tByte = inputStream.read()) > 0) {
outputStream.write(tByte);
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
inputStream.close();
outputStream.close();
}
return false;
}
public static void main(String[] args) {
// 抓取优快云首页,输出
try {
UrlReptile.downLoadPage("http://www.youkuaiyun.com/");
} catch (Exception e) {
}
}
}