English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Simule l'authentification de connexion Weibo et la collecte de données

Préambule :

Les frères et sœurs sont venus, récemment, quelqu'un a demandé comment simuler la connexion de Weibo pour capturer des données, après l'avoir entendu, j'ai calmement pris une cigarette d'usine, et me suis dit en silence, c'est le moment pour toi, l'homme d'âge mûr, donc aujourd'hui, j'ai eu du temps pour organiser et discuter brièvement.

Premièrement :

Pour se connecter à Weibo, il est nécessaire de préconnecter, c'est-à-dire convertir le compte en base64chiffrement, cryptage RSA et demandehttp://login.sina.com.cn/sso/prelogin.phpL'obtention des paramètres nécessaires à la connexion via un lien, la chaîne de retour est telle que :

{"retcode":0,"servertime":1487292003,"pcid":"gz-9e1f24c9acdefb111e1c8078558c7d9c0bf2"nonce":"VHRDG1"pubkey":"EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443"rsakv":"1330428213"is_openlock":0,"lm":1,"smsurl":"https:\"}}/\/login.sina.com.cn\/sso\/msglogin?entry=weibo&mobile=18360903574&s=ea7a2e91c5f1d6da7f42aa87fe6963d0","showpin":0,"exectime":222}

Ensuite, voici le code de traitement pré登陆 :

/**
 * @author LongJin
 * @description Informations initiales de connexion<br> Retourne false si l'initialisation échoue
 * @return
 */
 public boolean preLogin(){
 boolean flag = false;
 try {
 su = new String(Base64.encodeBase64(URLEncoder.encode(username, "UTF-8").getBytes()));
 String url = "http:";//login.sina.com.cn/sso/prelogin.php?entry=weibo&rsakt=mod&checkpin=1&" +
  "client=ssologin.js(v1.4.5)&_=" + getTimestamp();
 url += "&su=" + su;
 String content;
 content = HttpUtils.getRequest(client, url);
 System.out.println("content------------" + content);
 JSONObject json = JSONObject.fromObject(content);
 System.out.println(json);
 servertime = json.getLong("servertime");
 nonce = json.getString("nonce");
 rsakv = json.getString("rsakv");
 pubkey = json.getString("pubkey");
 flag = encodePwd();
 } catch (UnsupportedEncodingException e) {
 System.out.println("L'exception UnsupportedEncoding est lancée");
 } catch (ClientProtocolException e) {
 System.out.println("Lancer une exception ClientProtocol");
 } catch (IOException e) {
 System.out.println("Lancer une exception IO");
 }
 return flag;
 }

Deuxièmement :

Obtenir les paramètres nécessaires à la connexion et utiliser la requête POSThttp://login.sina.com.cn/sso/login.phpEn utilisant les données de traitement pré登陆 après pré登陆 comme paramètres de la requête, le résultat est le suivant :

<html>
<head>
<meta http-equiv="Content"-Type" content="text"/html; charset=GBK" />
<title>新浪通行证</title>
<script charset="utf-8" src="http://i.sso.sina.com.cn/js/ssologin.js"></script>
</head>
<body>
正在登录 ...
<script>
try{sinaSSOController.setCrossDomainUrlList({"retcode":0,"arrURL":["http:\/\/passport.97973.com\/sso\/crossdomain?action=login&savestate=1518828005"http:\/\/passport.weibo.cn\/sso\/crossdomain?action=login&savestate=1"]});}
 catch(e){
 var msg = e.message;
 var img = new Image();
 var type = 1;
 img.src = 'http://login.sina.com.cn/sso/debuglog?msg=' + msg +'&type=' + type;
 }try{sinaSSOController.crossDomainAction('login',function(){location.replace('http://passport.weibo.com/wbsso/login?ssosavestate=1518828005&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&ticket=ST-NTUwODg3MjkxMQ==-1487292005-gz-FF56C545999F864FC6C7AB86FCA9FA4A-1&retcode=0');});}
 catch(e){
 var msg = e.message;
 var img = new Image();
 var type = 2;
 img.src = 'http://login.sina.com.cn/sso/debuglog?msg=' + msg +'&type=' + type;
 }
</script>
</body>
</html>

然后用正则截取其中我们想要的部分:location.replace('')中间部分,正则表达式为:

String regex = "location.replace\\('([\\s\\S]*?)'\\);";

将正则得到的结果进行处理,如果成功则使用get请求得到的链接,登录部分的代码如下:

/**
 * @author LongJin
 * @description 登录
 * @return true:登录成功
 */
 public boolean login() {
 if(preLogin()) {}}
 String url = "http:";//login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15);
 List<NameValuePair> parms = new ArrayList<NameValuePair>();
 parms.add(new BasicNameValuePair("entry", "weibo"));
 parms.add(new BasicNameValuePair("geteway", ""));1"));
 parms.add(new BasicNameValuePair("from", ""));
 parms.add(new BasicNameValuePair("savestate", ""));7"));
 parms.add(new BasicNameValuePair("useticket", ""));1"));
 parms.add(new BasicNameValuePair("pagerefer", "http:"));//login.sina.com.cn/sso/logout.php?entry=miniblog&r=http%3A%2F%2Fweibo.com%2Flogout.php%3Fbackurl%3D%2F"));
 parms.add(new BasicNameValuePair("vsnf", ""));1"));
 parms.add(new BasicNameValuePair("su", su));
 parms.add(new BasicNameValuePair("service", "miniblog"));
 parms.add(new BasicNameValuePair("servertime", servertime)); + ""));
 parms.add(new BasicNameValuePair("nonce", nonce));
 parms.add(new BasicNameValuePair("pwencode", "rsa"));2"));
 parms.add(new BasicNameValuePair("rsakv", rsakv));
 parms.add(new BasicNameValuePair("sp", sp));
 parms.add(new BasicNameValuePair("encoding", "UTF-8"));
 parms.add(new BasicNameValuePair("prelt", "182"));
 parms.add(new BasicNameValuePair("url", "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"));
 parms.add(new BasicNameValuePair("domain", "sina.com.cn"));
 parms.add(new BasicNameValuePair("returntype", "META"));
 try {
 String content = HttpUtils.postRequest(client, url, parms);
 System.out.println("content----------" + content);
 String regex = "location.replace\\('([\\s\\S]*?)'\\);";//\\(' '\\)特殊符转译 匹配('')里面的内容//location.replace([\\s\\S]*?);
 Pattern p = Pattern.compile(regex);
 Matcher m = p.matcher(content);
 if(m.find()) {
  System.out.println("ss = ");+m.group());
  location = m.group();1);
  if(location.contains("reason=")) {//Si vous êtes arrivé à cette étape, félicitations, une erreur s'est produite;
  errInfo = location.substring(location.indexOf("reason=")); + 7);
  errInfo = URLDecoder.decode(errInfo, "GBK");
  }
  System.out.println("location = ");+location);
  String result = HttpUtils.getRequest(client, location);//.substring(2, location.length()-2)
  int beginIndex = result.indexOf("(");
  int endIndex = result.lastIndexOf(")");
  result = result.substring(beginIndex+1, endIndex);//Extraire la chaîne JSON entre les parenthèses
  //content = URLDecoder.decode(content, "UTF-8
  JSONObject jsonObject = JSONObject.fromObject(result);//Convertir en json
  //Obtenir uniqueid+userdomain utilisé comme paramètre lors de l'accès
  uniqueid = jsonObject.getJSONObject("userinfo").getString("uniqueid");
  userdomain = jsonObject.getJSONObject("userinfo").getString("userdomain");
  System.out.println("result--------------" + result);
  return true;
  }
 }
 } catch (ClientProtocolException e) {
 System.out.println("Lancer une exception ClientProtocol");
 } catch (IOException e) {
 System.out.println("Lancer une exception IO");
 }
 }
 return false;
 }

Compléter le code de cryptage de mot de passe :

 private static String sina_js = "var sinaSSOEncoder=sinaSSOEncoder||{};(function(){var hexcase=0;var chrsz=8;this.hex_sha1=function(s){return binb2hex(core_sha1(str2binb(s),s.length*chrsz));};var core_sha1=function(x,len){x[len>>5]|=0x80<<(24-len%32);x[((len+64>>>9)<<4)+15]=len;var w=Array(80);var a=1732584193;var b=-271733879;var c=-1732584194;var d=271733878;var e=-1009589776){ var olda = a; var oldb = b; var oldc = c; var oldd = d; var olde = e; for (var j = 0; j <+=160; j8){ if (j <++) w[j] = x[i16j]; else w[j] = rol(w[j+] ^ w[j-3];-8];-14];-16],1); var t = safe_add(safe_add(rol(a,5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j))); e = d; d = c; c = rol(b,30); b = a; a = t;} a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); e = safe_add(e, olde);} return Array(a, b, c, d, e);}; var sha1_ft = function(t, b, c, d) { if (t <20) return (b & c) | ((~b) & d);if(t<40) return b ^ c ^ d;if(t<60) return (b & c) | (b & d) | (c & d); return b ^ c ^ d; };var sha1_kt = function(t) { return (t <20) & #63;1518500249: (t <40) & #63;1859775393: (t <60) & #63;-1894007588:-899497514); }; var safe_add = function(x, y) { var lsw = (x & 0xFFFF)+(y & 0xFFFF); var msw = (x >>16)+(y >>16)+(lsw >>16); return (msw <<16) | (lsw & 0xFFFF); }; var rol = function(num, cnt) { return (num << cnt) | (num >>> (32-cnt)); }; var str2binb = function(str) { var bin = Array(); var mask = (1<< chrsz)-1; for (var i = 0; i < str.length*chrsz; i+= chrsz) bin[i >>5] | = (str.charCodeAt(i/chrsz) & mask << (24-i%32; return bin; }; var binb2hex = function(binarray) { var hex_tab = hexcase?'0123456789ABCDEF':'0123456789abcdef';var str='';for(var i=0;i<binarray.length*4;i++{str+=hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8+4))&0xF)+hex_tab.charAt((binarray[i>>2]>>((3-i%4)*8))&0xF);}return str;};this.base64={encode:function(input){input=''+input;if(input=='')return '';var output='';var chr1,chr2,chr3='';var enc1,enc2,enc3,enc4='';var i=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1='';enc1>>>2);enc2((chr1&3)<<4)|(chr2>>>4);enc3((chr2&15)<<2)|(chr3>>>6);enc4='';enc3&63);if(isNaN(chr2)){enc3=enc4=64);else if(isNaN(chr3)){enc4=64);}output=output+this._keys.charAt(enc1)+this._keys.charAt(enc2)+this._keys.charAt(enc3)+this._keys.charAt(enc4);chr1='';enc2='';enc3='';enc1=enc2=enc3=enc4123456789+/='};}).call(sinaSSOEncoder);;(function(){var dbits;var canary=0xdeadbeefcafe;var j_lm=((canary&0xffffff)==0xefcafe);function BigInteger(a,b,c){if(a!=null)if('number'==typeof a)this.fromNumber(a,b,c);else if(b==null && 'string' !=typeof a)this.fromString(a,256);else this.fromString(a,b);}function nbi(){return new BigInteger(null);}function am1(i,x,w,j,c,n){while(--n>=0){var v=x*this[i++]+w[j+0x/000000);w[j4]=v&0x++ffffff;3function am}2(i,x,w,j,c,n){var xl=x&0x7fff,xh=x>>15;while(--n>=0){var l=this[i]&0x7fff;var h=this[i++]>>15;var m=xh*l+h*xl;l=xl*l+((m&0x7fff)<<15)+w[j+(c&0x3fffffff);c=(l>>>30)+(m>>>15)+xh*h+(c>>>30);w[j++]=l&0x3fffffff;}return c;}function am3(i,x,w,j,c,n){var xl=x&0x3fff,xh=x>>14;while(--n>=0){var l=this[i]&0x3fff;var h=this[i++]>>14;var m=xh*l+h*xl;l=xl*l+((m&0x3fff)<<14)+w[j+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&0xfffffff;}return c;}BigInteger.prototype.am=am3;dbits=28;BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=(1<<dbits)-1);BigInteger.prototype.DV=(1<<dbits);var BI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;var BI_RM='0123456789abcdefghijklmnopqrstuvwxyz';var BI_RC=new Array();var rr,vv;rr='0'.charCodeAt(0);for(vv=0;vv<=9;++vv)BI_RC[rr++]=vv;rr='a'.charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;rr='A'.charCodeAt(0);for(vv=10;vv<36;++vv)BI_RC[rr++]=vv;function int2char(n){return BI_RM.charAt(n);}function intAt(s,i){var c=BI_RC[s.charCodeAt(i)];return(c==null)?-1:c;}function bnpCopyTo(r){for(var i=this.t-1;i>=0;--;this.s=(x<0)&#i)r[i]=this[i];r.t=this.t;r.s=this.s;}function bnpFromInt(x){this.t=1:0;if(x>0)this[0]=x;else if(x<63;-1)this[0]=x-1DV;else this.t=0;}function nbv(i){var r=nbi();r.fromInt(i);return r;}function bnpFromString(s,b){var k;if(b==+;else{this.fromRadix(s,b);return;}this.t=0;this.s=0;var i=s.length,mi=false,sh=0;while(16)k=4;else if(b==8)k=3;else if(b==256)k=8;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2i>=0){var x=(k==--;s[i]&0xff:intAt(s,i);if(x<0){if(s.charAt(i)=='8))?')mi=true;continue;}mi=false;if(sh==0)this[this.t-=x;else if(sh++k>this.DB){this[this.t+]|=(x&((-1))<<sh;this[this.t1<<(this.DB-sh))-1]=(x>>(this.DB++sh));-else this[this.t}-1]|=x<<sh;sh+=k;if(sh>=this.DB)sh-=this.DB;}if(k==8&&(s[0]&0x80)!=0){this.s=-1;if(sh>0)this[this.t-1]|=((1<<(this.DB-sh))-1)<<sh;}this.clamp();if(mi)BigInteger.ZERO.subTo(this,this);}function bnpClamp(){var c=this.s&this.DM;while(this.t>0&&this[this.t-1==c)--this.t;}function bnToString(b){if(this.s<0)return '-'+this.negate().toString(b);var k;if(b==16)k=4;else if(b==8)k=3;else if(b==2)k=1;else if(b==32)k=5;else if(b==4)k=2sinon retourner this.toRadix(b);var km=(1<
/**
 * le mot de passe est crypté RSA
 * retourne false indique que l'encodage a échoué
 * @return
 */
 private boolean encodePwd() {
 Gestionnaire d'engines de script sem = new ScriptEngineManager();
 ScriptEngine se = sem.getEngineByName("javascript");
 try {
 // Utilisation du chiffrement JS, RSA, appel à la méthode interne JS. Je utilise ici une chaîne de caractères, mais elle peut également être placée directement dans un fichier puis lue, comme indiqué dans les commentaires ci-dessous.
 se.eval(sina_js);
 //Appel à la fonction interne JS pour le chiffrement
 if (se instanceof Invocable) {
 Invocable iv = (Invocable) se;
 sp = (String) iv.invokeFunction("getpass", this.password, this.servertime, this.nonce,
  this.pubkey);
 }
 /* FileReader fr = new FileReader("E:\\encoder.js");
 se.eval(fr);
 Invocable invocableEngine = (Invocable) se;
 String callbackvalue = (String) invocableEngine.invokeFunction("encodePwd", pubkey, servertime, nonce, password);
 sp = callbackvalue;*/
 return true;
 } catch (ScriptException e) {
 // TODO Auto-bloc catch généré
 //e.printStackTrace();
 } catch (NoSuchMethodException e) {
 // TODO Auto-bloc catch généré
 //e.printStackTrace();
 }
 errInfo = "L'échec de l'encodage du mot de passe!";
 return false;
 }
/**
* @author LongJin
* @description Retourne l'information d'erreur
* @return
*/
public String getErrInfo() {
return errInfo;
}

La partie de connexion est pratiquement terminée.

Enfin, procédons à la test de connexion et à l'extraction des données :

public static void main(String[] args) throws ClientProtocolException, IOException {
 SinaWeibo weibo = new SinaWeibo("**"}}***//Le compte et le mot de passe ne seront pas révélés ici
 if(weibo.login()) {
 System.out.println("Connexion réussie !");
 InputStream con= HttpUtils.getRequests(client, "http://weibo.com/u/"+uniqueid+userdomain);//Obtenir le flux d'entrée de la page personnelle
 String cont = readStreamByEncoding(con, "UTF-8//Convertir le flux d'entrée en chaîne
 String sb = HttpUtils.getText(cont);//Obtenir la partie de contenu textuel via jsoup
 //readStreamOutFileByEncoding(sb); Il est également possible d'écrire le contenu obtenu dans un fichier
 }
 System.out.println("Échec de la connexion !");
 } 
 }

Le résultat obtenu est :

text--------------J'ai voté pour l'option "Yi Jianlian". #MVP national# Le vote pour le joueur le plus valuable de la saison régulière (MVP) de cette saison est composé de représentants des membres du comité de presse de la Fédération chinoise de basket-ball, des représentants des médias locaux recommandés par les clubs, une voix de Sina, et nous transmettrons l'opinion des fans à la fédération. Quel est le MVP national de cette saison ? #MVP national#63;63;63;63;

L'ensemble du processus de connexion est terminé, j'espère que je pourrai recevoir des suggestions pour améliorer.

Voici la totalité du contenu de cet article. J'espère que le contenu de cet article peut vous aider dans vos études ou votre travail, et j'espère également que vous soutiendrez vivement le tutoriel de cri du cœur !

Déclaration : Le contenu de cet article est issu du réseau, propriété des auteurs respectifs. Le contenu est apporté par les utilisateurs d'Internet de manière spontanée et est téléversé directement. Ce site ne détient pas de droits de propriété, n'a pas été édité par l'homme, et n'assume aucune responsabilité juridique. Si vous trouvez du contenu suspect de violation de droits d'auteur, veuillez envoyer un e-mail à : notice#oldtoolbag.com (veuillez remplacer # par @ lors de l'envoi d'un e-mail pour signaler une violation, et fournir des preuves pertinentes. Une fois vérifié, ce site supprimera immédiatement le contenu suspect de violation de droits d'auteur.)

Vous pourriez aussi aimer