我是用的是OKHTTP,想模拟登陆学校的教务系统,我看了下网页源码,他提交表单之后先重定向到一个网址,然后那个网址又重定向到另一个网址 ,然后它再get到个人信息页面,我模拟了表单提交的情况,然后他就一直返回登陆页面的源码,这是啥情况?代码贴下:
public class HttpDemo {
    /**
     * 主函数,测试请求,提交表单
     *
     * @param args
     */
    public static void main(String[] args) {
       // HttpURLConnectionDemo httpURLConnectionDemo = new HttpURLConnectionDemo();
        JsoupDemo demo = new JsoupDemo();
        List<String> lists = demo.jsoupDemo();
        String username = "150******";
        String password = "07****";
        String lt = lists.get(0);
        String execution = lists.get(1);
        String _eventId = lists.get(2);
        String rmShow = lists.get(3);
        OKhttpDemo oKhttpDemo = new OKhttpDemo();
        String cookie = null;
        try {
        cookie = oKhttpDemo.getCookie();
        }catch (Exception e){
            e.printStackTrace();
        }
         oKhttpDemo.sendPostAsync(username,password,lt,execution,_eventId,rmShow,cookie);    }上面这段是模拟提交的主程序
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;import java.io.IOException;import java.util.ArrayList;
import java.util.List;/**
 * 通过Jsoup获取表单中隐藏域的值
 */
public class JsoupDemo {
                public List<String> jsoupDemo(){
                    List<String> list = new ArrayList<>();
                    String url=
                            "http://ids.wbu.edu.cn/authserver/login?service=http://my.wbu.edu.cn/index.portal";
                    try {
                        //解析URL获得document对象,相当于点击去了URL
                        Document document = Jsoup.connect(url).timeout(10000).get();
                        //获取网页源码中id为"casLoginFrom"的标签
                        Element element = document.getElementById("casLoginForm");
                        //选择标签内有type属性为hidden的标签
                        Elements elements = document.getElementsByAttributeValue("type","hidden");
                        //System.out.println(elements);
                        //获取标签的value值,并存入list集合
                        for (Element ele :elements) {
                            String value = ele.attr("value");
                            list.add(value);
                            //System.out.println(value);                        }
        } catch (IOException e) {
            e.printStackTrace();
        }        return list;
    }
}
上面这个是获取隐藏域的值
import okhttp3.*;import java.io.IOException;public class OKhttpDemo {    /**
     * 获取第一次访问的Cookie
     * @return
     * @throws IOException
     */
    public String getCookie() throws IOException{        String url1="http://ids.wbu.edu.cn/authserver/login?service=http://my.wbu.edu.cn/index.portal";        OkHttpClient c=new OkHttpClient();        Request req=new Request.Builder().url(url1).get().build();        Response response=c.newCall(req).execute();        String Set_Cookie = response.header("Set-Cookie");        String str = Set_Cookie.substring(0, Set_Cookie.indexOf(";"));        System.out.println(str);        return  str;
    }
    /**
     * 添加请求头信息,模拟登陆
     * @param username
     * @param password
     * @param lt
     * @param execution
     * @param _eventId
     * @param rmShow
     * @param cookie
     */
    public void sendPostAsync(String username,String password,String lt,String execution, String _eventId, String rmShow,String cookie){        OkHttpClient client=new OkHttpClient();        //创建一个表单对象        FormBody formBody=new FormBody.Builder()                //添加表单内容                .add("username",username)                .add("password",password)                .add("lt",lt)                .add("execution",execution)                .add("_eventId",_eventId)                .add("rmShow",rmShow)                .build();        //创建一个请求        Request request=new Request.Builder()                //添加url                .url("http://ids.wbu.edu.cn/authserver/login?service=http://my.wbu.edu.cn/index.portal")                //添加请求头
                .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")                .addHeader("Accept-Encoding","gzip, deflate")                .addHeader("Accept-Language","zh-CN,zh;q=0.9")                .addHeader("Cache-Control","no-cache")                .addHeader("Connection","keep-alive")                .addHeader("Content-Type","application/x-www-form-urlencoded")                .addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36")                .addHeader("Origin"," http://ids.wbu.edu.cn")                .addHeader("Referer","http://ids.wbu.edu.cn/authserver/login?service=http://my.wbu.edu.cn/index.portal")                .addHeader("Cookie",cookie)                //设置请求对象                .post(formBody).build();        Call call=client.newCall(request);        call.enqueue(new Callback(){            //这里是异步操作\//请求失败时调用            @Override            public void onFailure(Call p1, IOException p2){            // TODO: Implement this method p2.printStackTrace();        }        @Override        public void onResponse(Call p1, Response p2) throws IOException{        // TODO: Implement this method        //获取响应内容        String responseContent=p2.body().string();        System.out.println(responseContent);    }    });}}
上面这个是模拟登陆的逻辑
这是登陆页面信息这是第一次重定向网址这是第一次重定向传递的参数这是第一次重定向的消息内容这是第二次重定向的网址这是第二次重定向的消息内容这是最后get到的个人信息的页面

解决方案 »

  1.   

    是不是登录后没保存cookie?导致get后还是没有登录的JSESSIONID,也不一致
      

  2.   

    我正准备写一个爬虫专栏,有兴趣可以一起学习。你这个需求其它用python可能就一,二十行左右就可以了。后面我会在个人主页上更新
      

  3.   

    是的,不一致,修改了,然后我想请问,他登陆之后post到第一个302界面,我简称3021,然后他又302到另一个页面,这个我简称3022然后他在3022哪里重新传了个cookie,这个cookie后面操作要用到,3022后他又200get到最终主页面,我现在想知道3022的新cookie我怎么获取到?
      

  4.   

    我去访问课表页面打印了cookie和登陆的cookie是一样的,但是他就是提示我先登录
      

  5.   

    public Map<String, String> login() throws IOException {
    Response res = null;
    Connection connect = Jsoup.connect(URL);
    // 伪造请求头
    connect.header("Accept",
    "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    connect.header("Accept-Language",
    "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
    .header("Connection", "keep-alive");
    connect.header("Content-Type", "application/x-www-form-urlencoded").header("Content-Length", "124");
    connect.header("Host", "www.kanyanbao.com").header("Referer",
    "https://www.kanyanbao.com/user/login.htm");
    connect.header("User-Agent",
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0")
    .header("Upgrade-Insecure-Requests", "1");

    res = connect.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0").timeout(10000).execute();
    connect.cookies(res.cookies());
    // connect.cookie("JSESSIONID", "6b88869ef03a375baf73ff5ae466")
    // .cookie("JSESSIONIDVERSION", "2f:10").cookie("JREPLICA", "instance234").cookie("ROUTEID", ".4")
    // .cookie("REPORT_SESSION_COOKIE", "xcVvDhEO5kyJSWUrOU1qmEPcr%2BxQftsPFphg49XNnWKyt0KRskZZAF9ag3dv5XumZ0UJDJY70XaM%0Aoy3CYeAHHA%3D%3D")
    // .cookie("REPORT_USERCOOKIE_USERNAME", "15810721521");
    // 携带登陆信息
    connect.data("username", USERNAME).data("password", PASSWORD).data("login_submit", "1").data("remember_name", "1"); // 请求url获取响应信息

    int tryTime = 10;
    while (tryTime > 0) {
    try {
    res = connect.ignoreContentType(true).method(Method.POST).execute();// 执行请求
    break;
    } catch (IOException e) {
    logger.error("getPrice jsoup " + tryTime + "/" + tryTime
    + " connect get occur an exception,detail is:"
    + e.getMessage());
    tryTime--;
    /** 线程休眠10秒钟 start **/
    try {
    int sleepSeconds = 10;
    // 休眠5秒
    Thread.sleep(sleepSeconds*1000);
    } catch (InterruptedException e2) {
    e2.printStackTrace();
    }
    /** 线程休眠10秒钟 end **/
    if (tryTime == 0) {
    try {
    throw new IOException(
    "getPrice jsoup connection failed.");
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    }
    }
    // 获取返回的cookie
    return res.cookies();
    }这是我的,希望对你有用