在用Java的HttpURLConnection 来下载网页,发现访问google的网站时,会被google拒绝掉。
try
{
url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
// logger.info(httpConn.getResponseMessage());
in = httpConn.getInputStream();
out = new FileOutputStream(new File(outPath));
chByte = in.read();
while (chByte != -1)
{
out.write(chByte);
chByte = in.read();
}
}
catch (MalformedURLException e)
{
}
}
经过一段时间的研究和查找资料,发现是由于上面的代码缺少了一些必要的信息导致,增加更加详细的属性
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
完整代码如下
public static void DownLoadPages(String urlStr, String outPath)
{
int chByte = 0;
URL url = null;
HttpURLConnection httpConn = null;
InputStream in = null;
FileOutputStream out = null;
try
{
url = new URL(urlStr);
httpConn = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
// logger.info(httpConn.getResponseMessage());
in = httpConn.getInputStream();
out = new FileOutputStream(new File(outPath));
chByte = in.read();
while (chByte != -1)
{
out.write(chByte);
chByte = in.read();
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
out.close();
in.close();
httpConn.disconnect();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
此外,还有第二种方法可以访问Google的网站,就是用apache的一个工具HttpClient 模仿一个浏览器来访问Google
Document document = null;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.setFollowRedirects(true);
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK)
{
InputStream in = getMethod.getResponseBodyAsStream();
InputSource is = new InputSource(in);
DOMParser domParser = new DOMParser(); //nekoHtml 将取得的网页转换成dom
domParser.parse(is);
document = domParser.getDocument();
System.out.println(getMethod.getURI());
}
return document;
推荐使用第一种方式,使用HttpConnection 比较轻量级,速度也比第二种HttpClient 的快。
一些代码,使用HttpUrlConnection来模拟ie form登陆web
关于java模拟ie form登陆web的问题
HttpURLConnection urlConn=(HttpURLConnection)(new URL(url).openConnection());
urlConn.addRequestProperty("Cookie",cookie);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
urlConn.setFollowRedirects(true);
urlConn.setDoOutput(true); // 需要向服务器写数据
urlConn.setDoInput(true); //
urlConn.setUseCaches(false); // 获得服务器最新的信息
urlConn.setAllowUserInteraction(false);
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConn.setRequestProperty("Content-Language","en-US" );
urlConn.setRequestProperty("Content-Length", ""+data.length());
DataOutputStream outStream = new DataOutputStream(urlConn.getOutputStream());
outStream.writeBytes(data);
outStream.flush();
outStream.close();
cookie=urlConn.getHeaderField("Set-Cookie");
BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"gb2312"));
Java制作自动访问网站机器人!
关键字: java制作自动访问网站机器人!
真的很久很久没有写过文章了,唉,惭愧啊!寒暄的说话就不多说了,直入主题。有人问过我,如何制作一些论坛的自动发言机器人?我说,这很简单啊,(如果没有图片验证码的话!)在Java里,有些URL,URLConnection的类啊,这些类可以访问一个URL获取数据,可以发送Request,你就可以结合一些类做一个自动发言的了,但用Post发送表单的话,就没有直接的,比较麻烦,如果还要处理Cookie的话,之后我想了想,想到了可以用 Jakarta Commons 下面的开源项目啊,有一个项目名叫“HttpClient”的,这个就是用Java写的Http客户端,可以说是一个简单功能的浏览器吧,只是不能解析 HTML标签,写这个解析可不是易事。既然我们是写个自动访问网站的程序,就不用解析显示HTML啦。朋友说能写个招聘网站的自动刷新简历的程序就好了,那就用51job为例吧。
首先,你得去下载HttpClient的包。
http://jakarta.apache.org/commons/httpclient
代码不多,我们就先来看看代码吧:
- import java.io.*;
- import org.apache.commons.httpclient.*;
- import org.apache.commons.httpclient.methods.*;
- public class HttpTest {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) {
- //先建立一个客户端实例,将模拟一个浏览器
- HttpClient client = new HttpClient();
- //这个是URL地址,我经过分析51job网站登录后的跳转到的地址,并分析得它在JavaScript里提交的URL的参数,不同网站就自已分析了,这个就是登录后刷新简历的URL地址
- String url = "http://my.51job.com/my/Pop_RefreshResume.php?en=0&ReSumeID=88888888&Read=0&ID=88888888";
- //之后再建立一个Post方法请求,提交刷新简历的表单,因为提交的参数较多,所以用Post请求好了
- PostMethod method = new PostMethod(url);
- //下面的就是将要提交的表单的数据填入PostMethod对象里面,以name , value 对加入!
- method.addParameter("HPNation", "086");
- method.addParameter("HPCity","020");
- method.addParameter("HPNumber","88888888");
- method.addParameter("FPNation","086");
- method.addParameter("FPCity","020");
- method.addParameter("FPNumber","88888888");
- method.addParameter("FPExtension","000");
- method.addParameter("MPNation","086");
- method.addParameter("Mobile","13888888888");
- method.addParameter("EmailAdd","888@888.com");
- method.addParameter("ReSumeID","88888888");
- //这里是建立请求时服务器需要用到的Cookie。
- Cookie cookie = new Cookie(".51job.com","51job","ccry%3D.0%252FZKBaMTmj82%26%7C%26cconfirmkey%3DcpwWgp7FC9FZM%26%7C%26cresumeid%3D88888888%26%7C%26cresumeids88888888d888826%7C8408ilstatus%3D2%26%7C%26cnickname826cenglis8cautologin%3D","/",null,false);
- //将设置好的Cookie加入模拟的客户端里。当请求发生时,就会将Cookie写进请求头里了
- client.getState().addCookie(cookie);
- int i=0;
- //开始死循环
- while(true){
- try{
- //这里是要求客户端发送一个请求。直接将PostMethod请求出去。
- client.executeMethod(method);
- //下面是获取返回的结果
- InputStream in = method.getResponseBodyAsStream();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buff = new byte[1024];
- int len = -1;
- while((len=in.read(buff))!=-1){
- baos.write(buff, 0, len);
- }
- String result = new String(baos.toByteArray());
- //释放资源
- in.close();
- baos.close();
- //在51job里,刷新简历成功的话,会返回一些JavaScript代码,里面有个alert()输出“简历已刷新”的信息的,你分析结果,如果有这句话,则成功刷新了。之后就让线程睡眠1分钟后循环刷新!
- if(result.indexOf("简历已刷新")!=-1){
- System.out.println("简历已刷新! " + ++i);
- }else{
- System.out.println("刷新失败!");
- }
- Thread.sleep(60000);
- }catch(Exception ex){
- System.out.println("******** Error! ********");
- try{
- //出现错误时,再等待20秒后再重新进行刷新。
- Thread.sleep(20000);
- }catch(Exception e){
- System.out.println("******** Thread Error! ********");
- }
- }
- }
- }
- }
import java.io.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
public class HttpTest {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) {
//先建立一个客户端实例,将模拟一个浏览器
HttpClient client = new HttpClient();
//这个是URL地址,我经过分析51job网站登录后的跳转到的地址,并分析得它在JavaScript里提交的URL的参数,不同网站就自已分析了,这个就是登录后刷新简历的URL地址
String url = "http://my.51job.com/my/Pop_RefreshResume.php?en=0&ReSumeID=88888888&Read=0&ID=88888888";
//之后再建立一个Post方法请求,提交刷新简历的表单,因为提交的参数较多,所以用Post请求好了
PostMethod method = new PostMethod(url);
//下面的就是将要提交的表单的数据填入PostMethod对象里面,以name , value 对加入!
method.addParameter("HPNation", "086");
method.addParameter("HPCity","020");
method.addParameter("HPNumber","88888888");
method.addParameter("FPNation","086");
method.addParameter("FPCity","020");
method.addParameter("FPNumber","88888888");
method.addParameter("FPExtension","000");
method.addParameter("MPNation","086");
method.addParameter("Mobile","13888888888");
method.addParameter("EmailAdd","888@888.com");
method.addParameter("ReSumeID","88888888");
//这里是建立请求时服务器需要用到的Cookie。
Cookie cookie = new Cookie(".51job.com","51job","ccry%3D.0%252FZKBaMTmj82%26%7C%26cconfirmkey%3DcpwWgp7FC9FZM%26%7C%26cresumeid%3D88888888%26%7C%26cresumeids88888888d888826%7C8408ilstatus%3D2%26%7C%26cnickname826cenglis8cautologin%3D","/",null,false);
//将设置好的Cookie加入模拟的客户端里。当请求发生时,就会将Cookie写进请求头里了
client.getState().addCookie(cookie);
int i=0;
//开始死循环
while(true){
try{
//这里是要求客户端发送一个请求。直接将PostMethod请求出去。
client.executeMethod(method);
//下面是获取返回的结果
InputStream in = method.getResponseBodyAsStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = -1;
while((len=in.read(buff))!=-1){
baos.write(buff, 0, len);
}
String result = new String(baos.toByteArray());
//释放资源
in.close();
baos.close();
//在51job里,刷新简历成功的话,会返回一些JavaScript代码,里面有个alert()输出“简历已刷新”的信息的,你分析结果,如果有这句话,则成功刷新了。之后就让线程睡眠1分钟后循环刷新!
if(result.indexOf("简历已刷新")!=-1){
System.out.println("简历已刷新! " + ++i);
}else{
System.out.println("刷新失败!");
}
Thread.sleep(60000);
}catch(Exception ex){
System.out.println("******** Error! ********");
try{
//出现错误时,再等待20秒后再重新进行刷新。
Thread.sleep(20000);
}catch(Exception e){
System.out.println("******** Thread Error! ********");
}
}
}
}
}
我们再来看看,其实很简单,我们来说明一下。HttpClient将很多Http协议底层的东西都封装了,这样很方便使用,如果自已用Socket写的话,还有处理很多信息,Http协议的三次握手等等的操作,很是麻烦。现在用HttpClient就一步到位了。但要注意一下,51job里面的简历刷新是要先登录后才可以进行的,而熟悉Web开发的人员都知道,登录后服务器就会记录下你的Session,而Session也是基于Cookie的,所以 Session ID是以Cookie的方式记录在客户机的,这样每次请求都要将该Cookie发送到服务器验证,这样才可以保证Web的状态。所以,你可以在浏览器里先登录一次。之后找出该网站的Cookie文件,将里面的内容复制出来放上上面代码的Cookie类里面。你也可以用这个HttpClient写一个登录的请求,之后再从ResponseHeader里获取Cookie。至于表单里的信息,就按自已需要填写就行了。就是模拟一个浏览器,将你的简历刷新的表单模拟出来再发送。