Jsoup實現微博登陸及發微博(帶驗證碼)

城堡

前言

很早之前用別的語言寫過一次微博登陸,現在改成java版,主要是為了驗證jsoup的強大,一款完全可勝任http請求和html解析的工具。抓包,抽取js的方法這里就不在贅述。

工具

  • jsoup-1.11.2(使用最新)
  • 打碼賬號及官方提供的java類(市面上很多,這里用若快)

開始

  1. 首先是分析登錄過程,常登陸的沒有驗證碼,新的會有驗證碼,保險起見這里都采用有驗證碼的方式登錄。
  2. Base64編碼用戶名后,get請求獲取servertime,nonce,pubkey,pcid,及返回的cookie
        //Base64編碼用戶名
        su = new BASE64Encoder().encode(usename.getBytes());
        String url = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su=" + su + "&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.18)&_=" +
                getTimestamp();
        Connection.Response execute = Jsoup.connect(url).ignoreContentType(true).execute();
        //獲取返回數據
        String body = execute.body();
        //獲取返回cookie
        Map<String, String> photocookie = execute.cookies();
        JSONObject jsonObject = JSONObject.parseObject(StringUtils.substringBetween(body, "(", ")"));
        servertime = jsonObject.getString("servertime");
        nonce = jsonObject.getString("nonce");
        pubkey = jsonObject.getString("pubkey");
        pcid = jsonObject.getString("pcid");
    
  3. 帶著返回的cookie及pcid,get請求獲取驗證碼
        url = "http://login.sina.com.cn/cgi/pin.php?r=54474015&s=0&p=" + pcid;
        byte[] bytes = Jsoup.connect(url).ignoreContentType(true).cookies(photocookie).execute().bodyAsBytes();
    
  4. 調用打碼平臺的類實現打碼,返回結果
    public static String createByPost(String username, String password, String typeid, String timeout, String softid, String softkey,byte[] byteArr) {
        String result = "";
        String param = String
                .format(
                        "username=%s&password=%s&typeid=%s&timeout=%s&softid=%s&softkey=%s",
                        username, password, typeid, timeout, softid, softkey);
        try {
            result = RuoKuai.httpPostImage("http://api.ruokuai.com/create.xml", param, byteArr);
            // jsoup去解析xml (略坑,加了好多參數進去)
            result = Jsoup.parse(result).select("body > root > result").text();
        } catch(Exception e) {
            result = "未知問題";
        }
        return result;
    }
    
  5. 調用js,對密碼動態加密,返回參數sp
    private boolean encodePwd() {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("javascript");
        try {
            // FileReader fr = new FileReader("");
            se.eval(LOGIN_JS);
            Invocable invocableEngine = (Invocable) se;
            sp = (String) invocableEngine.invokeFunction("getPW", password, servertime, nonce, pubkey);
            return true;
        } catch (ScriptException e) {
        } catch (NoSuchMethodException e) {
        }
        return false;
    }
    
  6. 帶著參數pcid,code,sp,su,servertime,nonce,sp及cookie,post請求返回cookies及下一個url,此時可從返回的body中判斷登錄成功與否
        //retcode=101 賬號密碼錯誤
        //retcode=80 請輸入正確的密碼
        //retcode=4049 輸入驗證碼
        //retcode=2070 驗證碼錯誤
        url = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.18)";
        String post = "entry=weibo&gateway=1&from=&savestate=7&useticket=1&pagerefer=http%3A%2F%2Fpassport.weibo" +
                ".com%2Fvisitor%2Fvisitor%3Fentry%3Dminiblog%26a%3Denter%26url%3Dhttp%253A%252F%252Fweibo.com%252F%26domain%3D.weibo" +
                ".com%26ua%3Dphp-sso_sdk_client-0.6.14%26_rand%3D1441434306.495&pcid=" + pcid + "&door=" + code + "&vsnf=1&su=" + su + "&service=miniblog&servertime=" + servertime + "&nonce=" + nonce
                + "&pwencode=rsa2&rsakv=1330428213&sp=" + sp + "&sr=1366*768&encoding=UTF-8&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META";
    
        Connection.Response execute1 = Jsoup.connect(url).method(Connection.Method.POST).requestBody(post).cookies(photocookie).ignoreContentType(true).execute().charset("GBK");
        String body1 = execute1.body();
        Map<String, String> cookies = execute1.cookies();
        System.out.println(body1);
        System.out.println(body1.indexOf("正在登錄") != -1 ? "登錄成功" : "登錄失敗");
    
        url = StringUtils.substringBetween(body1, "location.replace('", "'");
    
    
  7. 帶著上次返回的cookie,get請求(禁止重定向)獲取最終的cookie
        Connection.Response execute2 = Jsoup.connect(url).cookies(cookies).followRedirects(false).ignoreContentType(true).execute();
        Map<String, String> cookies1 = execute2.cookies();
        //從返回協議頭中獲取location,重定向地址,一般是固定
        Map<String, String> headers = execute2.headers();
    

結束

獲取到cookie,基本之后的操作都可以,那就簡單的發條微博,發微博其實只帶post數據和cookie就能提交,協議頭完全可以不帶,偏偏jsoup默認帶個UA,結果要多帶個refrere頭才可以。

  1. 通過步驟7,獲取的重定向地址,get請求獲取refrere參數uniqueid
      url = "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack&sudaref=login.sina.com.cn";
      String body2 = Jsoup.connect(url).cookies(cookies1).ignoreContentType(true).execute().body();
      String uid = StringUtils.substringBetween(body2, "uniqueid\":\"", "\",\"userid");
      String referer = "https://weibo.com/u/" + uid + "/home";
    
  2. 帶著cookie,及協議頭referer,post請求,發一條微博吧
      url = "https://weibo.com/aj/mblog/add?ajwvr=6&__rnd=" + getTimestamp();
      post = "location=v6_content_home&appkey=&style_type=1&pic_id=&text=" + text + "&pdetail=&rank=0&rankid=&module=stissue&pub_source=main_&pub_type=dialog&_t=0";
    
      Connection.Response execute3 = Jsoup.connect(url).method(Connection.Method.POST).requestBody(post).cookies(cookies1).referrer(referer).ignoreContentType(true).execute().charset("GBK");
      System.out.println(execute3.body());
    
Success
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,837評論 18 139
  • 轉載,覺得這篇寫 SQLAlchemy Core,寫得非常不錯。不過后續他沒寫SQLAlchemy ORM... ...
    非夢nj閱讀 5,462評論 1 14
  • 一、概念(載錄于:http://www.cnblogs.com/EricaMIN1987_IT/p/3837436...
    yuantao123434閱讀 8,413評論 6 152
  • Http協議詳解 標簽(空格分隔): Linux 聲明:本片文章非原創,內容來源于博客園作者MIN飛翔的HTTP協...
    Sivin閱讀 5,251評論 3 82
  • 寫一封情書 有生以來的第一封情書 在上面勾畫一只小海貝 托著比它重萬倍的重物 說去追逐它的愛戀 天空飄來一朵云 儼...
    海心沉思之花閱讀 207評論 0 0