基於httpclient的一個簡單刷票器實現
阿新 • • 發佈:2019-02-08
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去訪問下一個頁面,獲取相關資料後提交投票請求。