您的位置:首页 > 理论基础 > 计算机网络

基于httpclient的一个简单刷票器实现

2013-06-05 22:35 323 查看
package cn.ustb.edu.bean;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class Hello {
public static void main(String[] args) throws Exception {
File file = new File("G:/aaa.txt");
InputStreamReader read = new InputStreamReader(new FileInputStream(
file), "GBK");
BufferedReader bufferedReader = new BufferedReader(read);
String lineTXT = null;
String username = "", password = "";
String split[] = new String[2];

while ((lineTXT = bufferedReader.readLine()) != null) {
split = lineTXT.toString().trim().split("\\s{1,}");
username = split[0];
password = split[1];

// 请求认证借口,获取cookie
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(
"pollurl");
client.executeMethod(get);
String html = get.getResponseBodyAsString();
get.releaseConnection();
Document document = Jsoup.parse(html);
Elements element = document.select("input[name=csrf_token]");
String csrf = element.get(0).attr("value");
get.releaseConnection();

PostMethod post1 = new PostMethod(
"pollurl");
System.err.println( username+":"+password );
NameValuePair namePair[] = {
new NameValuePair("username", username ),
new NameValuePair("password", password ),
new NameValuePair("login", "1"),
new NameValuePair("csrf_token", csrf) };
post1.setRequestBody(namePair);
int state = client.executeMethod(post1);
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match("vote.ibeike.com", 80, "",
false, client.getState().getCookies());
String coo = "";
for (Cookie cookie : cookies) {
System.out.println(cookie.toString());
coo = cookie.toString();
}
post1.releaseConnection();

PostMethod post2 = new PostMethod(
"pollurl");
NameValuePair namePair1[] = {
new NameValuePair("checked[]", "16"),  // youjia
new NameValuePair("csrf_token", csrf),
new NameValuePair("isPoll", "1") };
post2.setRequestBody( namePair1 );
state = client.executeMethod(post2);

Thread.sleep(3000);
}
read.close();
}
}
aaa.txt文件里面放置的是用户名和密码,用来登录这个投票网站的,格式大概为: username     password 中间是空格
主要是运用httpclient登录网站,获取Cookie,然后带着Cookie去访问下一个页面,获取相关数据后提交投票请求。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐