Jsoup模拟登陆小例子,不同的网站,需要不同的模拟策略,散仙在这里仅仅作为一个引导学习。
- package com.jsouplogin;
-
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- import org.jsoup.Connection;
- import org.jsoup.Jsoup;
- import org.jsoup.Connection.Method;
- import org.jsoup.Connection.Response;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
-
- public class JsoupLoginIteye {
-
- public static void main(String[] args)throws Exception {
-
- JsoupLoginIteye jli=new JsoupLoginIteye();
- jli.login("xxxxx", "xxxxx");
-
- }
-
- public void login(String userName,String pwd)throws Exception{
-
-
- Connection con=Jsoup.connect("http://www.iteye.com/login");//获取连接
- con.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
- Response rs= con.execute();
- Document d1=Jsoup.parse(rs.body());
- List<Element> et= d1.select("#login_form");
-
-
- Map<String, String> datas=new HashMap<>();
- for(Element e:et.get(0).getAllElements()){
- if(e.attr("name").equals("name")){
- e.attr("value", userName);
- }
-
- if(e.attr("name").equals("password")){
- e.attr("value",pwd);
- }
-
- if(e.attr("name").length()>0){
- datas.put(e.attr("name"), e.attr("value"));
- }
- }
-
-
-
- Connection con2=Jsoup.connect("http://www.iteye.com/login");
- con2.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
-
- Response login=con2.ignoreContentType(true).method(Method.POST).data(datas).cookies(rs.cookies()).execute();
-
- System.out.println(login.body());
-
-
- Map<String, String> map=login.cookies();
- for(String s:map.keySet()){
- System.out.println(s+" "+map.get(s));
- }
-
- }
-
-
-
-
-
-
- }
posted @
2015-11-12 20:30
zfswff
阅读(
312)
评论()
编辑
收藏
举报