java实现微博后台登录发送微博
首先你需要有个微博开发者账号,我们需要的是AppKey和AppSecre及redirect_URI,公司原本就有所以这一步省下来了,百度搜下有很多。
好了现在开始:
首先我在网上找到了这个代码,这里写链接内容
本来挺高兴的一次性解决了嘛;可是报错“token刷新失败”,看了下代码
返回的是200不是302,额有点懵了,不管了先研究研究为什么会这样吧,我将他生成的网址放到浏览器上看了下,进入的是授权页面,不会需要先登录。F12看了下确实也是200,于是我估计是不是因为没有登录成功的原因,于是开始做微博的后台登录
找到这样一篇代码,原地址已经忘了,原作者不好意思啊。
packagecom.spider.httpclient; importjava.io.BufferedReader; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.net.URI; importjava.net.URISyntaxException; importjava.net.URLEncoder; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; importjavax.script.Invocable; importjavax.script.ScriptEngine; importjavax.script.ScriptEngineManager; importjavax.script.ScriptException; importorg.apache.commons.codec.binary.Base64; importorg.apache.http.Header; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.NameValuePair; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.HttpClient; importorg.apache.http.client.config.CookieSpecs; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.config.Registry; importorg.apache.http.config.RegistryBuilder; importorg.apache.http.cookie.CookieSpec; importorg.apache.http.cookie.CookieSpecProvider; importorg.apache.http.impl.client.BasicCookieStore; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.impl.cookie.DefaultCookieSpec; importorg.apache.http.impl.cookie.DefaultCookieSpecProvider; importorg.apache.http.message.BasicNameValuePair; importorg.apache.http.protocol.HttpContext; importorg.apache.http.util.EntityUtils; importcom.alibaba.fastjson.JSONArray; importcom.alibaba.fastjson.JSONObject; /** *新浪微博登录器,2016年4月7日08:30:16,密码加密方式采用RSA2,加密方式js内 * *@authortom * */ publicclassSinaWeiboLogger{ privateHttpClientclient; privateHttpPostpost; privateHttpGetget; privateBasicCookieStorecookieStore; privateStringusername;//明文账号 privateStringpassword;//明文密码 privateStringsu;//base64加密后账号 privateStringsp;//RSA加密后密码 //预登陆信息所需数据开始 privatelongservertime;//服务器时间戳 privateStringnonce;//服务器返回字符串 privateStringrsakv;//服务器返回字符串,rsa加密密码用 privateStringpubkey;//服务器返回rsa加密公用密钥,用于rsa加密 privateintretcode;//状态值 privateStringpcid; privateintis_openlock; privateintshowpin; privateintexectime; //预登陆信息结束 //登录后返回json数据 privateStringuid; privateStringnick; privateJSONArraydomainurls; // privateStringBufferheaderCookie=newStringBuffer(); //登录密码加密js文件内容 privatestaticStringsina_js="varsinaSSOEncoder=sinaSSOEncoder||{};(function(){varhexcase=0;varchrsz=8;this.hex_sha1=function(s){returnbinb2hex(core_sha1(str2binb(s),s.length*chrsz));};varcore_sha1=function(x,len){x[len>>5]|=0x80<<(24-len%32);x[((len+64>>9)<<4)+15]=len;varw=Array(80);vara=1732584193;varb=-271733879;varc=-1732584194;vard=271733878;vare=-1009589776;for(vari=0;i<x.length;i+=16){varolda=a;varoldb=b;varoldc=c;varoldd=d;varolde=e;for(varj=0;j<80;j++){if(j<16)w[j]=x[i+j];elsew[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);vart=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);}returnArray(a,b,c,d,e);};varsha1_ft=function(t,b,c,d){if(t<20)return(b&c)|((~b)&d);if(t<40)returnb^c^d;if(t<60)return(b&c)|(b&d)|(c&d);returnb^c^d;};varsha1_kt=function(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;};varsafe_add=function(x,y){varlsw=(x&0xFFFF)+(y&0xFFFF);varmsw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);};varrol=function(num,cnt){return(num<<cnt)|(num>>>(32-cnt));};varstr2binb=function(str){varbin=Array();varmask=(1<<chrsz)-1;for(vari=0;i<str.length*chrsz;i+=chrsz)bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(24-i%32);returnbin;};varbinb2hex=function(binarray){varhex_tab=hexcase?'0123456789ABCDEF':'0123456789abcdef';varstr='';for(vari=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);}returnstr;};this.base64={encode:function(input){input=''+input;if(input=='')return'';varoutput='';varchr1,chr2,chr3='';varenc1,enc2,enc3,enc4='';vari=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}elseif(isNaN(chr3)){enc4=64;}output=output+this._keys.charAt(enc1)+this._keys.charAt(enc2)+this._keys.charAt(enc3)+this._keys.charAt(enc4);chr1=chr2=chr3='';enc1=enc2=enc3=enc4='';}while(i<input.length);returnoutput;},_keys:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='};}).call(sinaSSOEncoder);;(function(){vardbits;varcanary=0xdeadbeefcafe;varj_lm=((canary&0xffffff)==0xefcafe);functionBigInteger(a,b,c){if(a!=null)if('number'==typeofa)this.fromNumber(a,b,c);elseif(b==null&&'string'!=typeofa)this.fromString(a,256);elsethis.fromString(a,b);}functionnbi(){returnnewBigInteger(null);}functionam1(i,x,w,j,c,n){while(--n>=0){varv=x*this[i++]+w[j]+c;c=Math.floor(v/0x4000000);w[j++]=v&0x3ffffff;}returnc;}functionam2(i,x,w,j,c,n){varxl=x&0x7fff,xh=x>>15;while(--n>=0){varl=this[i]&0x7fff;varh=this[i++]>>15;varm=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;}returnc;}functionam3(i,x,w,j,c,n){varxl=x&0x3fff,xh=x>>14;while(--n>=0){varl=this[i]&0x3fff;varh=this[i++]>>14;varm=xh*l+h*xl;l=xl*l+((m&0x3fff)<<14)+w[j]+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&0xfffffff;}returnc;}BigInteger.prototype.am=am3;dbits=28;BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<<dbits)-1);BigInteger.prototype.DV=(1<<dbits);varBI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;varBI_RM='0123456789abcdefghijklmnopqrstuvwxyz';varBI_RC=newArray();varrr,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;functionint2char(n){returnBI_RM.charAt(n);}functionintAt(s,i){varc=BI_RC[s.charCodeAt(i)];return(c==null)?-1:c;}functionbnpCopyTo(r){for(vari=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t;r.s=this.s;}functionbnpFromInt(x){this.t=1;this.s=(x<0)?-1:0;if(x>0)this[0]=x;elseif(x<-1)this[0]=x+DV;elsethis.t=0;}functionnbv(i){varr=nbi();r.fromInt(i);returnr;}functionbnpFromString(s,b){vark;if(b==16)k=4;elseif(b==8)k=3;elseif(b==256)k=8;elseif(b==2)k=1;elseif(b==32)k=5;elseif(b==4)k=2;else{this.fromRadix(s,b);return;}this.t=0;this.s=0;vari=s.length,mi=false,sh=0;while(--i>=0){varx=(k==8)?s[i]&0xff:intAt(s,i);if(x<0){if(s.charAt(i)=='-')mi=true;continue;}mi=false;if(sh==0)this[this.t++]=x;elseif(sh+k>this.DB){this[this.t-1]|=(x&((1<<(this.DB-sh))-1))<<sh;this[this.t++]=(x>>(this.DB-sh));}elsethis[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);}functionbnpClamp(){varc=this.s&this.DM;while(this.t>0&&this[this.t-1]==c)--this.t;}functionbnToString(b){if(this.s<0)return'-'+this.negate().toString(b);vark;if(b==16)k=4;elseif(b==8)k=3;elseif(b==2)k=1;elseif(b==32)k=5;elseif(b==4)k=2;elsereturnthis.toRadix(b);varkm=(1<<k)-1,d,m=false,r='',i=this.t;varp=this.DB-(i*this.DB)%k;if(i-->0){if(p<this.DB&&(d=this[i]>>p)>0){m=true;r=int2char(d);}while(i>=0){if(p<k){d=(this[i]&((1<<p)-1))<<(k-p);d|=this[--i]>>(p+=this.DB-k);}else{d=(this[i]>>(p-=k))&km;if(p<=0){p+=this.DB;--i;}}if(d>0)m=true;if(m)r+=int2char(d);}}returnm?r:'0';}functionbnNegate(){varr=nbi();BigInteger.ZERO.subTo(this,r);returnr;}functionbnAbs(){return(this.s<0)?this.negate():this;}functionbnCompareTo(a){varr=this.s-a.s;if(r!=0)returnr;vari=this.t;r=i-a.t;if(r!=0)returnr;while(--i>=0)if((r=this[i]-a[i])!=0)returnr;return0;}functionnbits(x){varr=1,t;if((t=x>>>16)!=0){x=t;r+=16;}if((t=x>>8)!=0){x=t;r+=8;}if((t=x>>4)!=0){x=t;r+=4;}if((t=x>>2)!=0){x=t;r+=2;}if((t=x>>1)!=0){x=t;r+=1;}returnr;}functionbnBitLength(){if(this.t<=0)return0;returnthis.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));}functionbnpDLShiftTo(n,r){vari;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n;r.s=this.s;}functionbnpDRShiftTo(n,r){for(vari=n;i<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0);r.s=this.s;}functionbnpLShiftTo(n,r){varbs=n%this.DB;varcbs=this.DB-bs;varbm=(1<<cbs)-1;vards=Math.floor(n/this.DB),c=(this.s<<bs)&this.DM,i;for(i=this.t-1;i>=0;--i){r[i+ds+1]=(this[i]>>cbs)|c;c=(this[i]&bm)<<bs;}for(i=ds-1;i>=0;--i)r[i]=0;r[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp();}functionbnpRShiftTo(n,r){r.s=this.s;vards=Math.floor(n/this.DB);if(ds>=this.t){r.t=0;return;}varbs=n%this.DB;varcbs=this.DB-bs;varbm=(1<<bs)-1;r[0]=this[ds]>>bs;for(vari=ds+1;i<this.t;++i){r[i-ds-1]|=(this[i]&bm)<<cbs;r[i-ds]=this[i]>>bs;}if(bs>0)r[this.t-ds-1]|=(this.s&bm)<<cbs;r.t=this.t-ds;r.clamp();}functionbnpSubTo(a,r){vari=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]-a[i];r[i++]=c&this.DM;c>>=this.DB;}if(a.t<this.t){c-=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB;}c+=this.s;}else{c+=this.s;while(i<a.t){c-=a[i];r[i++]=c&this.DM;c>>=this.DB;}c-=a.s;}r.s=(c<0)?-1:0;if(c<-1)r[i++]=this.DV+c;elseif(c>0)r[i++]=c;r.t=i;r.clamp();}functionbnpMultiplyTo(a,r){varx=this.abs(),y=a.abs();vari=x.t;r.t=i+y.t;while(--i>=0)r[i]=0;for(i=0;i<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0;r.clamp();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r);}functionbnpSquareTo(r){varx=this.abs();vari=r.t=2*x.t;while(--i>=0)r[i]=0;for(i=0;i<x.t-1;++i){varc=x.am(i,x[i],r,2*i,0,1);if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=x.DV){r[i+x.t]-=x.DV;r[i+x.t+1]=1;}}if(r.t>0)r[r.t-1]+=x.am(i,x[i],r,2*i,0,1);r.s=0;r.clamp();}functionbnpDivRemTo(m,q,r){varpm=m.abs();if(pm.t<=0)return;varpt=this.abs();if(pt.t<pm.t){if(q!=null)q.fromInt(0);if(r!=null)this.copyTo(r);return;}if(r==null)r=nbi();vary=nbi(),ts=this.s,ms=m.s;varnsh=this.DB-nbits(pm[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r);}else{pm.copyTo(y);pt.copyTo(r);}varys=y.t;vary0=y[ys-1];if(y0==0)return;varyt=y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);vard1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2;vari=r.t,j=i-ys,t=(q==null)?nbi():q;y.dlShiftTo(j,t);if(r.compareTo(t)>=0){r[r.t++]=1;r.subTo(t,r);}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t<ys)y[y.t++]=0;while(--j>=0){varqd=(r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))<qd){y.dlShiftTo(j,t);r.subTo(t,r);while(r[i]<--qd)r.subTo(t,r);}}if(q!=null){r.drShiftTo(ys,q);if(ts!=ms)BigInteger.ZERO.subTo(q,q);}r.t=ys;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r);}functionbnMod(a){varr=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);returnr;}functionClassic(m){this.m=m;}functioncConvert(x){if(x.s<0||x.compareTo(this.m)>=0)returnx.mod(this.m);elsereturnx;}functioncRevert(x){returnx;}functioncReduce(x){x.divRemTo(this.m,null,x);}functioncMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}functioncSqrTo(x,r){x.squareTo(r);this.reduce(r);}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;functionbnpInvDigit(){if(this.t<1)return0;varx=this[0];if((x&1)==0)return0;vary=x&3;y=(y*(2-(x&0xf)*y))&0xf;y=(y*(2-(x&0xff)*y))&0xff;y=(y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;y=(y*(2-x*y%this.DV))%this.DV;return(y>0)?this.DV-y:-y;}functionMontgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&0x7fff;this.mph=this.mp>>15;this.um=(1<<(m.DB-15))-1;this.mt2=2*m.t;}functionmontConvert(x){varr=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);returnr;}functionmontRevert(x){varr=nbi();x.copyTo(r);this.reduce(r);returnr;}functionmontReduce(x){while(x.t<=this.mt2)x[x.t++]=0;for(vari=0;i<this.m.t;++i){varj=x[i]&0x7fff;varu0=(j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;j=i+this.m.t;x[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x[j]>=x.DV){x[j]-=x.DV;x[++j]++;}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x);}functionmontSqrTo(x,r){x.squareTo(r);this.reduce(r);}functionmontMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;functionbnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0;}functionbnpExp(e,z){if(e>0xffffffff||e<1)returnBigInteger.ONE;varr=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;g.copyTo(r);while(--i>=0){z.sqrTo(r,r2);if((e&(1<<i))>0)z.mulTo(r2,g,r);else{vart=r;r=r2;r2=t;}}returnz.revert(r);}functionbnModPowInt(e,m){varz;if(e<256||m.isEven())z=newClassic(m);elsez=newMontgomery(m);returnthis.exp(e,z);}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);functionArcfour(){this.i=0;this.j=0;this.S=newArray();}functionARC4init(key){vari,j,t;for(i=0;i<256;++i)this.S[i]=i;j=0;for(i=0;i<256;++i){j=(j+this.S[i]+key[i%key.length])&255;t=this.S[i];this.S[i]=this.S[j];this.S[j]=t;}this.i=0;this.j=0;}functionARC4next(){vart;this.i=(this.i+1)&255;this.j=(this.j+this.S[this.i])&255;t=this.S[this.i];this.S[this.i]=this.S[this.j];this.S[this.j]=t;returnthis.S[(t+this.S[this.i])&255];}Arcfour.prototype.init=ARC4init;Arcfour.prototype.next=ARC4next;functionprng_newstate(){returnnewArcfour();}varrng_psize=256;varrng_state;varrng_pool;varrng_pptr;functionrng_seed_int(x){rng_pool[rng_pptr++]^=x&255;rng_pool[rng_pptr++]^=(x>>8)&255;rng_pool[rng_pptr++]^=(x>>16)&255;rng_pool[rng_pptr++]^=(x>>24)&255;if(rng_pptr>=rng_psize)rng_pptr-=rng_psize;}functionrng_seed_time(){rng_seed_int(newDate().getTime());}if(rng_pool==null){rng_pool=newArray();rng_pptr=0;vart;while(rng_pptr<rng_psize){t=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=t>>>8;rng_pool[rng_pptr++]=t&255;}rng_pptr=0;rng_seed_time();}functionrng_get_byte(){if(rng_state==null){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0;}returnrng_state.next();}functionrng_get_bytes(ba){vari;for(i=0;i<ba.length;++i)ba[i]=rng_get_byte();}functionSecureRandom(){}SecureRandom.prototype.nextBytes=rng_get_bytes;functionparseBigInt(str,r){returnnewBigInteger(str,r);}functionlinebrk(s,n){varret='';vari=0;while(i+n<s.length){ret+=s.substring(i,i+n)+'\\n';i+=n;}returnret+s.substring(i,s.length);}functionbyte2Hex(b){if(b<0x10)return'0'+b.toString(16);elsereturnb.toString(16);}functionpkcs1pad2(s,n){if(n<s.length+11){returnnull;}varba=newArray();vari=s.length-1;while(i>=0&&n>0){varc=s.charCodeAt(i--);if(c<128){ba[--n]=c;}elseif((c>127)&&(c<2048)){ba[--n]=(c&63)|128;ba[--n]=(c>>6)|192;}else{ba[--n]=(c&63)|128;ba[--n]=((c>>6)&63)|128;ba[--n]=(c>>12)|224;}}ba[--n]=0;varrng=newSecureRandom();varx=newArray();while(n>2){x[0]=0;while(x[0]==0)rng.nextBytes(x);ba[--n]=x[0];}ba[--n]=2;ba[--n]=0;returnnewBigInteger(ba);}functionRSAKey(){this.n=null;this.e=0;this.d=null;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null;}functionRSASetPublic(N,E){if(N!=null&&E!=null&&N.length>0&&E.length>0){this.n=parseBigInt(N,16);this.e=parseInt(E,16);}elsealert('InvalidRSApublickey');}functionRSADoPublic(x){returnx.modPowInt(this.e,this.n);}functionRSAEncrypt(text){varm=pkcs1pad2(text,(this.n.bitLength()+7)>>3);if(m==null)returnnull;varc=this.doPublic(m);if(c==null)returnnull;varh=c.toString(16);if((h.length&1)==0)returnh;elsereturn'0'+h;}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;this.RSAKey=RSAKey;}).call(sinaSSOEncoder);functiongetpass(pwd,servicetime,nonce,rsaPubkey){varRSAKey=newsinaSSOEncoder.RSAKey();RSAKey.setPublic(rsaPubkey,'10001');varpassword=RSAKey.encrypt([servicetime,nonce].join('\\t')+'\\n'+pwd);returnpassword;}"; publicSinaWeiboLogger(Stringusername,Stringpassword){ this.username=username; this.password=password; //cookie策略,不设置会拒绝cookierejected,设置策略保存cookie信息 cookieStore=newBasicCookieStore(); CookieSpecProvidermyCookie=newCookieSpecProvider(){ publicCookieSpeccreate(HttpContextcontext){ returnnewDefaultCookieSpec(); } }; Registry<CookieSpecProvider>rg=RegistryBuilder.<CookieSpecProvider>create().register("myCookie",myCookie) .build(); client=HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCookieSpecRegistry(rg).build(); get=newHttpGet(); post=newHttpPost(); } /** *预登陆,使用用户名base64加密后get请求,得到返回值,使用返回值加密用户密码再次请求 * *@throwsIOException *@throwsClientProtocolException *@throwsURISyntaxException */ privatevoidpreLogin()throwsClientProtocolException,IOException,URISyntaxException{ //1 su=newString(Base64.encodeBase64(URLEncoder.encode(this.username,"UTF-8").getBytes())); StringpreLoginUrl="http://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=" +su+"&rsakt=mod&client=ssologin.js(v1.4.15)&_="+newDate().getTime(); get.setURI(newURI(preLoginUrl)); get.addHeader("Host","login.sina.com.cn"); get.addHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:45.0)Gecko/20100101Firefox/45.0"); get.addHeader("Accept","*/*"); get.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); get.addHeader("Accept-Encoding","gzip,deflate"); get.addHeader("Referer","http://login.sina.com.cn/"); get.addHeader("Connection","keep-alive"); HttpResponseresp=client.execute(get); //保存请求返回cookie,登录后请求其他页面需要带cookie saveCookie(resp.getAllHeaders(),this.headerCookie); HttpEntityentity=resp.getEntity(); Stringcont=EntityUtils.toString(entity); //System.out.println(cont); cont=cont.replace("sinaSSOController.preloginCallBack(",""); cont=cont.replace(")",""); JSONObjectjson=JSONObject.parseObject(cont); this.retcode=json.getIntValue("retcode"); this.servertime=json.getLongValue("servertime"); this.pcid=json.getString("pcid"); this.nonce=json.getString("nonce"); this.pubkey=json.getString("pubkey"); this.rsakv=json.getString("rsakv"); this.is_openlock=json.getIntValue("is_openlock"); this.showpin=json.getIntValue("showpin"); this.exectime=json.getIntValue("exectime"); } privatevoidsaveCookie(Header[]headers,StringBufferheaderCookie){ for(Headerh:headers){ if(h.getName().equals("Set-Cookie")){ headerCookie.append(h.getValue()).append(";"); } } } /** *登录新浪通行证账号登录,加密密码,post请求 * *@return * *@throwsIOException *@throwsClientProtocolException *@throwsScriptException *@throwsNoSuchMethodException *@throwsURISyntaxException */ privatevoidaccountLogin()throwsNoSuchMethodException,ScriptException,ClientProtocolException,IOException,URISyntaxException{ //2 StringloginUrl="http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=" +newDate().getTime(); post.setURI(newURI(loginUrl)); post.addHeader("Host","login.sina.com.cn"); post.addHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:45.0)Gecko/20100101Firefox/45.0"); post.addHeader("Accept","*/*"); post.addHeader("Content-Type","application/x-www-form-urlencoded"); post.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); post.addHeader("Accept-Encoding","gzip,deflate"); post.addHeader("Referer","http://login.sina.com.cn/"); post.addHeader("Connection","keep-alive"); //使用js加密密码,RSA,调用js内方法 ScriptEngineManagersem=newScriptEngineManager(); ScriptEnginese=sem.getEngineByName("javascript"); se.eval(sina_js); if(seinstanceofInvocable){ Invocableiv=(Invocable)se; sp=(String)iv.invokeFunction("getpass",this.password,this.servertime,this.nonce, this.pubkey); } List<NameValuePair>parms=newArrayList<NameValuePair>(); parms.add(newBasicNameValuePair("entry","account")); parms.add(newBasicNameValuePair("gateway","1")); parms.add(newBasicNameValuePair("from","")); parms.add(newBasicNameValuePair("savestate","0")); parms.add(newBasicNameValuePair("useticket","0")); parms.add(newBasicNameValuePair("pagerefer","")); parms.add(newBasicNameValuePair("vsnf","1")); parms.add(newBasicNameValuePair("su",su)); parms.add(newBasicNameValuePair("service","sso")); parms.add(newBasicNameValuePair("servertime",servertime+"")); parms.add(newBasicNameValuePair("nonce",nonce)); parms.add(newBasicNameValuePair("pwencode","rsa2")); parms.add(newBasicNameValuePair("rsakv",rsakv)); parms.add(newBasicNameValuePair("sp",sp)); parms.add(newBasicNameValuePair("sr","1366*768")); parms.add(newBasicNameValuePair("encoding","UTF-8")); parms.add(newBasicNameValuePair("cdult","3")); parms.add(newBasicNameValuePair("domain","sina.com.cn")); parms.add(newBasicNameValuePair("prelt","51")); parms.add(newBasicNameValuePair("returntype","TEXT")); post.setEntity(newUrlEncodedFormEntity(parms)); HttpResponseresp=client.execute(post); //保存请求返回cookie,登录后请求其他页面需要带cookie saveCookie(resp.getAllHeaders(),this.headerCookie); //请求返回链接 JSONObjectjsonObj=JSONObject.parseObject(EntityUtils.toString(resp.getEntity())); System.out.println(jsonObj.toJSONString()); this.retcode=jsonObj.getIntValue("retcode"); this.uid=jsonObj.getString("uid"); this.nick=jsonObj.getString("nick"); this.domainurls=jsonObj.getJSONArray("crossDomainUrlList"); List<String>retMsg=newArrayList<String>(); inti=0; for(Objecturl:domainurls){ get.setURI(newURI(url.toString()+"&callback=sinaSSOController.doCrossDomainCallBack&scriptId=ssoscript"+i+"&client=ssologin.js(v1.4.15)&_="+newDate().getTime())); resp=client.execute(get); retMsg.add(EntityUtils.toString(resp.getEntity())); i++; } get.setURI(newURI("http://login.sina.com.cn/member/my.php?entry=sso")); //添加请求cookie到请求头 get.addHeader("Cookie",this.headerCookie.toString()); resp=client.execute(get); Stringcont=readStreamByEncoding(resp.getEntity().getContent(),"GBK"); retMsg.add(cont); for(Strings:retMsg){ System.out.println(s); } } privateStringreadStreamByEncoding(InputStreamin,Stringencoding)throwsIOException{ StringBuffercont=newStringBuffer(); BufferedReaderbr=newBufferedReader(newInputStreamReader(in,encoding)); Stringtmp=""; while((tmp=br.readLine())!=null){ cont.append(tmp); } br.close(); returncont.toString(); } /** *登录 */ publicvoidlogin(){ try{ this.preLogin(); this.accountLogin(); }catch(ClientProtocolExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); }catch(NoSuchMethodExceptione){ e.printStackTrace(); }catch(ScriptExceptione){ e.printStackTrace(); }catch(URISyntaxExceptione){ e.printStackTrace(); } } publicHttpClientgetClient(){ returnclient; } publicvoidsetClient(HttpClientclient){ this.client=client; } publicHttpPostgetPost(){ returnpost; } publicvoidsetPost(HttpPostpost){ this.post=post; } publicHttpGetgetGet(){ returnget; } publicvoidsetGet(HttpGetget){ this.get=get; } publicStringgetUsername(){ returnusername; } publicvoidsetUsername(Stringusername){ this.username=username; } publicStringgetSu(){ returnsu; } publicvoidsetSu(Stringsu){ this.su=su; } publicStringgetSp(){ returnsp; } publicvoidsetSp(Stringsp){ this.sp=sp; } publicStringgetNonce(){ returnnonce; } publicvoidsetNonce(Stringnonce){ this.nonce=nonce; } publicStringgetRsakv(){ returnrsakv; } publicvoidsetRsakv(Stringrsakv){ this.rsakv=rsakv; } publicStringgetPubkey(){ returnpubkey; } publicvoidsetPubkey(Stringpubkey){ this.pubkey=pubkey; } publicintgetRetcode(){ returnretcode; } publicvoidsetRetcode(intretcode){ this.retcode=retcode; } publicStringgetUid(){ returnuid; } publicvoidsetUid(Stringuid){ this.uid=uid; } publicStringgetNick(){ returnnick; } publicvoidsetNick(Stringnick){ this.nick=nick; } publicstaticStringgetSina_js(){ returnsina_js; } publicBasicCookieStoregetCookieStore(){ returncookieStore; } publicvoidsetCookieStore(BasicCookieStorecookieStore){ this.cookieStore=cookieStore; } publicstaticvoidmain(String[]args){ newSinaWeiboLogger("","").login(); } }
登录相当成功,于是我在这代码的基础上加上了些修改,运行后代码报Connectionreset这个错误;
经过研究发现其实已经授权成功了,不过在授权成功后页面会进行两次重定向所以报这个错。于是又开始各种百度,这里写链接内容。
这个上面终于找到我要的东西
/** *根据给定的链接获取所有的重定向位置 *@paramlink给定的链接 *@return *@throwsClientProtocolException *@throwsIOException */ publicList<URI>getAllRedirectLocations(Stringlink)throwsClientProtocolException,IOException{ List<URI>redirectLocations=null; CloseableHttpResponseresponse=null; try{ HttpClientContextcontext=HttpClientContext.create(); HttpGethttpGet=newHttpGet(link); response=httpClient.execute(httpGet,context); //获取所有的重定向位置 redirectLocations=context.getRedirectLocations(); }finally{ if(response!=null){ response.close(); } } returnredirectLocations; }
就这样再配合微博的SDK,一套从微博登录到发送微博的操作就完成啦,完整代码如下:
packageweibo4j.examples.test; importjava.io.IOException; importjava.net.URI; importjava.net.URISyntaxException; importjava.net.URLEncoder; importjava.text.SimpleDateFormat; importjava.util.ArrayList; importjava.util.Date; importjava.util.List; importjavax.script.Invocable; importjavax.script.ScriptEngine; importjavax.script.ScriptEngineManager; importjavax.script.ScriptException; importorg.apache.commons.codec.binary.Base64; importorg.apache.commons.httpclient.HttpException; importorg.apache.http.Header; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.NameValuePair; importorg.apache.http.client.ClientProtocolException; importorg.apache.http.client.HttpClient; importorg.apache.http.client.entity.UrlEncodedFormEntity; importorg.apache.http.client.methods.CloseableHttpResponse; importorg.apache.http.client.methods.HttpGet; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.client.protocol.HttpClientContext; importorg.apache.http.config.Registry; importorg.apache.http.config.RegistryBuilder; importorg.apache.http.cookie.CookieSpec; importorg.apache.http.cookie.CookieSpecProvider; importorg.apache.http.impl.client.BasicCookieStore; importorg.apache.http.impl.client.HttpClients; importorg.apache.http.impl.cookie.DefaultCookieSpec; importorg.apache.http.message.BasicNameValuePair; importorg.apache.http.protocol.HttpContext; importorg.apache.http.util.EntityUtils; importweibo4j.Oauth; importweibo4j.Timeline; importweibo4j.http.AccessToken; importweibo4j.model.Status; importweibo4j.model.WeiboException; importweibo4j.util.WeiboConfig; importcom.alibaba.fastjson.JSONArray; importcom.alibaba.fastjson.JSONObject; /** *新浪微博登录器,2016年4月7日08:30:16,密码加密方式采用RSA2,加密方式js内 * *@authortom * */ publicclassSinaWeiboLogger{ privateHttpClientclient; privateHttpPostpost; privateHttpGetget; privateBasicCookieStorecookieStore; privateStringusername;//明文账号 privateStringpassword;//明文密码 privateStringsu;//base64加密后账号 privateStringsp;//RSA加密后密码 //预登陆信息所需数据开始 privatelongservertime;//服务器时间戳 privateStringnonce;//服务器返回字符串 privateStringrsakv;//服务器返回字符串,rsa加密密码用 privateStringpubkey;//服务器返回rsa加密公用密钥,用于rsa加密 privateintretcode;//状态值 privateStringpcid; privateintis_openlock; privateintshowpin; privateintexectime; //预登陆信息结束 //登录后返回json数据 privateStringuid; privateStringnick; privateJSONArraydomainurls; // StringclientId=WeiboConfig.getValue("client_ID"); StringredirectURI=WeiboConfig.getValue("redirect_URI"); StringauthorizeURL=WeiboConfig.getValue("authorizeURL"); privateStringBufferheaderCookie=newStringBuffer(); //登录密码加密js文件内容 privatestaticStringsina_js="varsinaSSOEncoder=sinaSSOEncoder||{};(function(){varhexcase=0;varchrsz=8;this.hex_sha1=function(s){returnbinb2hex(core_sha1(str2binb(s),s.length*chrsz));};varcore_sha1=function(x,len){x[len>>5]|=0x80<<(24-len%32);x[((len+64>>9)<<4)+15]=len;varw=Array(80);vara=1732584193;varb=-271733879;varc=-1732584194;vard=271733878;vare=-1009589776;for(vari=0;i<x.length;i+=16){varolda=a;varoldb=b;varoldc=c;varoldd=d;varolde=e;for(varj=0;j<80;j++){if(j<16)w[j]=x[i+j];elsew[j]=rol(w[j-3]^w[j-8]^w[j-14]^w[j-16],1);vart=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);}returnArray(a,b,c,d,e);};varsha1_ft=function(t,b,c,d){if(t<20)return(b&c)|((~b)&d);if(t<40)returnb^c^d;if(t<60)return(b&c)|(b&d)|(c&d);returnb^c^d;};varsha1_kt=function(t){return(t<20)?1518500249:(t<40)?1859775393:(t<60)?-1894007588:-899497514;};varsafe_add=function(x,y){varlsw=(x&0xFFFF)+(y&0xFFFF);varmsw=(x>>16)+(y>>16)+(lsw>>16);return(msw<<16)|(lsw&0xFFFF);};varrol=function(num,cnt){return(num<<cnt)|(num>>>(32-cnt));};varstr2binb=function(str){varbin=Array();varmask=(1<<chrsz)-1;for(vari=0;i<str.length*chrsz;i+=chrsz)bin[i>>5]|=(str.charCodeAt(i/chrsz)&mask)<<(24-i%32);returnbin;};varbinb2hex=function(binarray){varhex_tab=hexcase?'0123456789ABCDEF':'0123456789abcdef';varstr='';for(vari=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);}returnstr;};this.base64={encode:function(input){input=''+input;if(input=='')return'';varoutput='';varchr1,chr2,chr3='';varenc1,enc2,enc3,enc4='';vari=0;do{chr1=input.charCodeAt(i++);chr2=input.charCodeAt(i++);chr3=input.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}elseif(isNaN(chr3)){enc4=64;}output=output+this._keys.charAt(enc1)+this._keys.charAt(enc2)+this._keys.charAt(enc3)+this._keys.charAt(enc4);chr1=chr2=chr3='';enc1=enc2=enc3=enc4='';}while(i<input.length);returnoutput;},_keys:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='};}).call(sinaSSOEncoder);;(function(){vardbits;varcanary=0xdeadbeefcafe;varj_lm=((canary&0xffffff)==0xefcafe);functionBigInteger(a,b,c){if(a!=null)if('number'==typeofa)this.fromNumber(a,b,c);elseif(b==null&&'string'!=typeofa)this.fromString(a,256);elsethis.fromString(a,b);}functionnbi(){returnnewBigInteger(null);}functionam1(i,x,w,j,c,n){while(--n>=0){varv=x*this[i++]+w[j]+c;c=Math.floor(v/0x4000000);w[j++]=v&0x3ffffff;}returnc;}functionam2(i,x,w,j,c,n){varxl=x&0x7fff,xh=x>>15;while(--n>=0){varl=this[i]&0x7fff;varh=this[i++]>>15;varm=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;}returnc;}functionam3(i,x,w,j,c,n){varxl=x&0x3fff,xh=x>>14;while(--n>=0){varl=this[i]&0x3fff;varh=this[i++]>>14;varm=xh*l+h*xl;l=xl*l+((m&0x3fff)<<14)+w[j]+c;c=(l>>28)+(m>>14)+xh*h;w[j++]=l&0xfffffff;}returnc;}BigInteger.prototype.am=am3;dbits=28;BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<<dbits)-1);BigInteger.prototype.DV=(1<<dbits);varBI_FP=52;BigInteger.prototype.FV=Math.pow(2,BI_FP);BigInteger.prototype.F1=BI_FP-dbits;BigInteger.prototype.F2=2*dbits-BI_FP;varBI_RM='0123456789abcdefghijklmnopqrstuvwxyz';varBI_RC=newArray();varrr,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;functionint2char(n){returnBI_RM.charAt(n);}functionintAt(s,i){varc=BI_RC[s.charCodeAt(i)];return(c==null)?-1:c;}functionbnpCopyTo(r){for(vari=this.t-1;i>=0;--i)r[i]=this[i];r.t=this.t;r.s=this.s;}functionbnpFromInt(x){this.t=1;this.s=(x<0)?-1:0;if(x>0)this[0]=x;elseif(x<-1)this[0]=x+DV;elsethis.t=0;}functionnbv(i){varr=nbi();r.fromInt(i);returnr;}functionbnpFromString(s,b){vark;if(b==16)k=4;elseif(b==8)k=3;elseif(b==256)k=8;elseif(b==2)k=1;elseif(b==32)k=5;elseif(b==4)k=2;else{this.fromRadix(s,b);return;}this.t=0;this.s=0;vari=s.length,mi=false,sh=0;while(--i>=0){varx=(k==8)?s[i]&0xff:intAt(s,i);if(x<0){if(s.charAt(i)=='-')mi=true;continue;}mi=false;if(sh==0)this[this.t++]=x;elseif(sh+k>this.DB){this[this.t-1]|=(x&((1<<(this.DB-sh))-1))<<sh;this[this.t++]=(x>>(this.DB-sh));}elsethis[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);}functionbnpClamp(){varc=this.s&this.DM;while(this.t>0&&this[this.t-1]==c)--this.t;}functionbnToString(b){if(this.s<0)return'-'+this.negate().toString(b);vark;if(b==16)k=4;elseif(b==8)k=3;elseif(b==2)k=1;elseif(b==32)k=5;elseif(b==4)k=2;elsereturnthis.toRadix(b);varkm=(1<<k)-1,d,m=false,r='',i=this.t;varp=this.DB-(i*this.DB)%k;if(i-->0){if(p<this.DB&&(d=this[i]>>p)>0){m=true;r=int2char(d);}while(i>=0){if(p<k){d=(this[i]&((1<<p)-1))<<(k-p);d|=this[--i]>>(p+=this.DB-k);}else{d=(this[i]>>(p-=k))&km;if(p<=0){p+=this.DB;--i;}}if(d>0)m=true;if(m)r+=int2char(d);}}returnm?r:'0';}functionbnNegate(){varr=nbi();BigInteger.ZERO.subTo(this,r);returnr;}functionbnAbs(){return(this.s<0)?this.negate():this;}functionbnCompareTo(a){varr=this.s-a.s;if(r!=0)returnr;vari=this.t;r=i-a.t;if(r!=0)returnr;while(--i>=0)if((r=this[i]-a[i])!=0)returnr;return0;}functionnbits(x){varr=1,t;if((t=x>>>16)!=0){x=t;r+=16;}if((t=x>>8)!=0){x=t;r+=8;}if((t=x>>4)!=0){x=t;r+=4;}if((t=x>>2)!=0){x=t;r+=2;}if((t=x>>1)!=0){x=t;r+=1;}returnr;}functionbnBitLength(){if(this.t<=0)return0;returnthis.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));}functionbnpDLShiftTo(n,r){vari;for(i=this.t-1;i>=0;--i)r[i+n]=this[i];for(i=n-1;i>=0;--i)r[i]=0;r.t=this.t+n;r.s=this.s;}functionbnpDRShiftTo(n,r){for(vari=n;i<this.t;++i)r[i-n]=this[i];r.t=Math.max(this.t-n,0);r.s=this.s;}functionbnpLShiftTo(n,r){varbs=n%this.DB;varcbs=this.DB-bs;varbm=(1<<cbs)-1;vards=Math.floor(n/this.DB),c=(this.s<<bs)&this.DM,i;for(i=this.t-1;i>=0;--i){r[i+ds+1]=(this[i]>>cbs)|c;c=(this[i]&bm)<<bs;}for(i=ds-1;i>=0;--i)r[i]=0;r[ds]=c;r.t=this.t+ds+1;r.s=this.s;r.clamp();}functionbnpRShiftTo(n,r){r.s=this.s;vards=Math.floor(n/this.DB);if(ds>=this.t){r.t=0;return;}varbs=n%this.DB;varcbs=this.DB-bs;varbm=(1<<bs)-1;r[0]=this[ds]>>bs;for(vari=ds+1;i<this.t;++i){r[i-ds-1]|=(this[i]&bm)<<cbs;r[i-ds]=this[i]>>bs;}if(bs>0)r[this.t-ds-1]|=(this.s&bm)<<cbs;r.t=this.t-ds;r.clamp();}functionbnpSubTo(a,r){vari=0,c=0,m=Math.min(a.t,this.t);while(i<m){c+=this[i]-a[i];r[i++]=c&this.DM;c>>=this.DB;}if(a.t<this.t){c-=a.s;while(i<this.t){c+=this[i];r[i++]=c&this.DM;c>>=this.DB;}c+=this.s;}else{c+=this.s;while(i<a.t){c-=a[i];r[i++]=c&this.DM;c>>=this.DB;}c-=a.s;}r.s=(c<0)?-1:0;if(c<-1)r[i++]=this.DV+c;elseif(c>0)r[i++]=c;r.t=i;r.clamp();}functionbnpMultiplyTo(a,r){varx=this.abs(),y=a.abs();vari=x.t;r.t=i+y.t;while(--i>=0)r[i]=0;for(i=0;i<y.t;++i)r[i+x.t]=x.am(0,y[i],r,i,0,x.t);r.s=0;r.clamp();if(this.s!=a.s)BigInteger.ZERO.subTo(r,r);}functionbnpSquareTo(r){varx=this.abs();vari=r.t=2*x.t;while(--i>=0)r[i]=0;for(i=0;i<x.t-1;++i){varc=x.am(i,x[i],r,2*i,0,1);if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1))>=x.DV){r[i+x.t]-=x.DV;r[i+x.t+1]=1;}}if(r.t>0)r[r.t-1]+=x.am(i,x[i],r,2*i,0,1);r.s=0;r.clamp();}functionbnpDivRemTo(m,q,r){varpm=m.abs();if(pm.t<=0)return;varpt=this.abs();if(pt.t<pm.t){if(q!=null)q.fromInt(0);if(r!=null)this.copyTo(r);return;}if(r==null)r=nbi();vary=nbi(),ts=this.s,ms=m.s;varnsh=this.DB-nbits(pm[pm.t-1]);if(nsh>0){pm.lShiftTo(nsh,y);pt.lShiftTo(nsh,r);}else{pm.copyTo(y);pt.copyTo(r);}varys=y.t;vary0=y[ys-1];if(y0==0)return;varyt=y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);vard1=this.FV/yt,d2=(1<<this.F1)/yt,e=1<<this.F2;vari=r.t,j=i-ys,t=(q==null)?nbi():q;y.dlShiftTo(j,t);if(r.compareTo(t)>=0){r[r.t++]=1;r.subTo(t,r);}BigInteger.ONE.dlShiftTo(ys,t);t.subTo(y,y);while(y.t<ys)y[y.t++]=0;while(--j>=0){varqd=(r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);if((r[i]+=y.am(0,qd,r,j,0,ys))<qd){y.dlShiftTo(j,t);r.subTo(t,r);while(r[i]<--qd)r.subTo(t,r);}}if(q!=null){r.drShiftTo(ys,q);if(ts!=ms)BigInteger.ZERO.subTo(q,q);}r.t=ys;r.clamp();if(nsh>0)r.rShiftTo(nsh,r);if(ts<0)BigInteger.ZERO.subTo(r,r);}functionbnMod(a){varr=nbi();this.abs().divRemTo(a,null,r);if(this.s<0&&r.compareTo(BigInteger.ZERO)>0)a.subTo(r,r);returnr;}functionClassic(m){this.m=m;}functioncConvert(x){if(x.s<0||x.compareTo(this.m)>=0)returnx.mod(this.m);elsereturnx;}functioncRevert(x){returnx;}functioncReduce(x){x.divRemTo(this.m,null,x);}functioncMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}functioncSqrTo(x,r){x.squareTo(r);this.reduce(r);}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;functionbnpInvDigit(){if(this.t<1)return0;varx=this[0];if((x&1)==0)return0;vary=x&3;y=(y*(2-(x&0xf)*y))&0xf;y=(y*(2-(x&0xff)*y))&0xff;y=(y*(2-(((x&0xffff)*y)&0xffff)))&0xffff;y=(y*(2-x*y%this.DV))%this.DV;return(y>0)?this.DV-y:-y;}functionMontgomery(m){this.m=m;this.mp=m.invDigit();this.mpl=this.mp&0x7fff;this.mph=this.mp>>15;this.um=(1<<(m.DB-15))-1;this.mt2=2*m.t;}functionmontConvert(x){varr=nbi();x.abs().dlShiftTo(this.m.t,r);r.divRemTo(this.m,null,r);if(x.s<0&&r.compareTo(BigInteger.ZERO)>0)this.m.subTo(r,r);returnr;}functionmontRevert(x){varr=nbi();x.copyTo(r);this.reduce(r);returnr;}functionmontReduce(x){while(x.t<=this.mt2)x[x.t++]=0;for(vari=0;i<this.m.t;++i){varj=x[i]&0x7fff;varu0=(j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;j=i+this.m.t;x[j]+=this.m.am(0,u0,x,i,0,this.m.t);while(x[j]>=x.DV){x[j]-=x.DV;x[++j]++;}}x.clamp();x.drShiftTo(this.m.t,x);if(x.compareTo(this.m)>=0)x.subTo(this.m,x);}functionmontSqrTo(x,r){x.squareTo(r);this.reduce(r);}functionmontMulTo(x,y,r){x.multiplyTo(y,r);this.reduce(r);}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;functionbnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0;}functionbnpExp(e,z){if(e>0xffffffff||e<1)returnBigInteger.ONE;varr=nbi(),r2=nbi(),g=z.convert(this),i=nbits(e)-1;g.copyTo(r);while(--i>=0){z.sqrTo(r,r2);if((e&(1<<i))>0)z.mulTo(r2,g,r);else{vart=r;r=r2;r2=t;}}returnz.revert(r);}functionbnModPowInt(e,m){varz;if(e<256||m.isEven())z=newClassic(m);elsez=newMontgomery(m);returnthis.exp(e,z);}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1);functionArcfour(){this.i=0;this.j=0;this.S=newArray();}functionARC4init(key){vari,j,t;for(i=0;i<256;++i)this.S[i]=i;j=0;for(i=0;i<256;++i){j=(j+this.S[i]+key[i%key.length])&255;t=this.S[i];this.S[i]=this.S[j];this.S[j]=t;}this.i=0;this.j=0;}functionARC4next(){vart;this.i=(this.i+1)&255;this.j=(this.j+this.S[this.i])&255;t=this.S[this.i];this.S[this.i]=this.S[this.j];this.S[this.j]=t;returnthis.S[(t+this.S[this.i])&255];}Arcfour.prototype.init=ARC4init;Arcfour.prototype.next=ARC4next;functionprng_newstate(){returnnewArcfour();}varrng_psize=256;varrng_state;varrng_pool;varrng_pptr;functionrng_seed_int(x){rng_pool[rng_pptr++]^=x&255;rng_pool[rng_pptr++]^=(x>>8)&255;rng_pool[rng_pptr++]^=(x>>16)&255;rng_pool[rng_pptr++]^=(x>>24)&255;if(rng_pptr>=rng_psize)rng_pptr-=rng_psize;}functionrng_seed_time(){rng_seed_int(newDate().getTime());}if(rng_pool==null){rng_pool=newArray();rng_pptr=0;vart;while(rng_pptr<rng_psize){t=Math.floor(65536*Math.random());rng_pool[rng_pptr++]=t>>>8;rng_pool[rng_pptr++]=t&255;}rng_pptr=0;rng_seed_time();}functionrng_get_byte(){if(rng_state==null){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr<rng_pool.length;++rng_pptr)rng_pool[rng_pptr]=0;rng_pptr=0;}returnrng_state.next();}functionrng_get_bytes(ba){vari;for(i=0;i<ba.length;++i)ba[i]=rng_get_byte();}functionSecureRandom(){}SecureRandom.prototype.nextBytes=rng_get_bytes;functionparseBigInt(str,r){returnnewBigInteger(str,r);}functionlinebrk(s,n){varret='';vari=0;while(i+n<s.length){ret+=s.substring(i,i+n)+'\\n';i+=n;}returnret+s.substring(i,s.length);}functionbyte2Hex(b){if(b<0x10)return'0'+b.toString(16);elsereturnb.toString(16);}functionpkcs1pad2(s,n){if(n<s.length+11){returnnull;}varba=newArray();vari=s.length-1;while(i>=0&&n>0){varc=s.charCodeAt(i--);if(c<128){ba[--n]=c;}elseif((c>127)&&(c<2048)){ba[--n]=(c&63)|128;ba[--n]=(c>>6)|192;}else{ba[--n]=(c&63)|128;ba[--n]=((c>>6)&63)|128;ba[--n]=(c>>12)|224;}}ba[--n]=0;varrng=newSecureRandom();varx=newArray();while(n>2){x[0]=0;while(x[0]==0)rng.nextBytes(x);ba[--n]=x[0];}ba[--n]=2;ba[--n]=0;returnnewBigInteger(ba);}functionRSAKey(){this.n=null;this.e=0;this.d=null;this.p=null;this.q=null;this.dmp1=null;this.dmq1=null;this.coeff=null;}functionRSASetPublic(N,E){if(N!=null&&E!=null&&N.length>0&&E.length>0){this.n=parseBigInt(N,16);this.e=parseInt(E,16);}elsealert('InvalidRSApublickey');}functionRSADoPublic(x){returnx.modPowInt(this.e,this.n);}functionRSAEncrypt(text){varm=pkcs1pad2(text,(this.n.bitLength()+7)>>3);if(m==null)returnnull;varc=this.doPublic(m);if(c==null)returnnull;varh=c.toString(16);if((h.length&1)==0)returnh;elsereturn'0'+h;}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;this.RSAKey=RSAKey;}).call(sinaSSOEncoder);functiongetpass(pwd,servicetime,nonce,rsaPubkey){varRSAKey=newsinaSSOEncoder.RSAKey();RSAKey.setPublic(rsaPubkey,'10001');varpassword=RSAKey.encrypt([servicetime,nonce].join('\\t')+'\\n'+pwd);returnpassword;}"; publicSinaWeiboLogger(Stringusername,Stringpassword){ this.username=username; this.password=password; //cookie策略,不设置会拒绝cookierejected,设置策略保存cookie信息 cookieStore=newBasicCookieStore(); CookieSpecProvidermyCookie=newCookieSpecProvider(){ publicCookieSpeccreate(HttpContextcontext){ returnnewDefaultCookieSpec(); } }; Registry<CookieSpecProvider>rg=RegistryBuilder.<CookieSpecProvider>create().register("myCookie",myCookie) .build(); client=HttpClients.custom().setDefaultCookieStore(cookieStore).setDefaultCookieSpecRegistry(rg).build(); get=newHttpGet(); post=newHttpPost(); } /** *预登陆,使用用户名base64加密后get请求,得到返回值,使用返回值加密用户密码再次请求 * *@throwsIOException *@throwsClientProtocolException *@throwsURISyntaxException */ privatevoidpreLogin()throwsClientProtocolException,IOException,URISyntaxException{ //1 su=newString(Base64.encodeBase64(URLEncoder.encode(this.username,"UTF-8").getBytes())); StringpreLoginUrl="http://login.sina.com.cn/sso/prelogin.php?entry=account&callback=sinaSSOController.preloginCallBack&su=" +su+"&rsakt=mod&client=ssologin.js(v1.4.15)&_="+newDate().getTime(); get.setURI(newURI(preLoginUrl)); get.addHeader("Host","login.sina.com.cn"); get.addHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:45.0)Gecko/20100101Firefox/45.0"); get.addHeader("Accept","*/*"); get.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); get.addHeader("Accept-Encoding","gzip,deflate"); get.addHeader("Referer","http://login.sina.com.cn/"); get.addHeader("Connection","keep-alive"); HttpResponseresp=client.execute(get); //保存请求返回cookie,登录后请求其他页面需要带cookie saveCookie(resp.getAllHeaders(),this.headerCookie); HttpEntityentity=resp.getEntity(); Stringcont=EntityUtils.toString(entity); //System.out.println(cont); cont=cont.replace("sinaSSOController.preloginCallBack(",""); cont=cont.replace(")",""); JSONObjectjson=JSONObject.parseObject(cont); this.retcode=json.getIntValue("retcode"); this.servertime=json.getLongValue("servertime"); this.pcid=json.getString("pcid"); this.nonce=json.getString("nonce"); this.pubkey=json.getString("pubkey"); this.rsakv=json.getString("rsakv"); this.is_openlock=json.getIntValue("is_openlock"); this.showpin=json.getIntValue("showpin"); this.exectime=json.getIntValue("exectime"); } privatevoidsaveCookie(Header[]headers,StringBufferheaderCookie){ for(Headerh:headers){ if(h.getName().equals("Set-Cookie")){ headerCookie.append(h.getValue()).append(";"); } } } /** *登录新浪通行证账号登录,加密密码,post请求 * *@return * *@throwsIOException *@throwsClientProtocolException *@throwsScriptException *@throwsNoSuchMethodException *@throwsURISyntaxException */ privateAccessTokenaccountLogin()throwsNoSuchMethodException,ScriptException,ClientProtocolException,IOException,URISyntaxException{ //2 StringloginUrl="http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=" +newDate().getTime(); post.setURI(newURI(loginUrl)); post.addHeader("Host","login.sina.com.cn"); post.addHeader("User-Agent","Mozilla/5.0(WindowsNT6.1;WOW64;rv:45.0)Gecko/20100101Firefox/45.0"); post.addHeader("Accept","*/*"); post.addHeader("Content-Type","application/x-www-form-urlencoded"); post.addHeader("Accept-Language","zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"); post.addHeader("Accept-Encoding","gzip,deflate"); post.addHeader("Referer","http://login.sina.com.cn/"); post.addHeader("Connection","keep-alive"); //使用js加密密码,RSA,调用js内方法 ScriptEngineManagersem=newScriptEngineManager(); ScriptEnginese=sem.getEngineByName("javascript"); se.eval(sina_js); if(seinstanceofInvocable){ Invocableiv=(Invocable)se; sp=(String)iv.invokeFunction("getpass",this.password,this.servertime,this.nonce, this.pubkey); } List<NameValuePair>parms=newArrayList<NameValuePair>(); parms.add(newBasicNameValuePair("entry","account")); parms.add(newBasicNameValuePair("gateway","1")); parms.add(newBasicNameValuePair("from","")); parms.add(newBasicNameValuePair("savestate","0")); parms.add(newBasicNameValuePair("useticket","0")); parms.add(newBasicNameValuePair("pagerefer","")); parms.add(newBasicNameValuePair("vsnf","1")); parms.add(newBasicNameValuePair("su",su)); parms.add(newBasicNameValuePair("service","sso")); parms.add(newBasicNameValuePair("servertime",servertime+"")); parms.add(newBasicNameValuePair("nonce",nonce)); parms.add(newBasicNameValuePair("pwencode","rsa2")); parms.add(newBasicNameValuePair("rsakv",rsakv)); parms.add(newBasicNameValuePair("sp",sp)); parms.add(newBasicNameValuePair("sr","1366*768")); parms.add(newBasicNameValuePair("encoding","UTF-8")); parms.add(newBasicNameValuePair("cdult","3")); parms.add(newBasicNameValuePair("domain","sina.com.cn")); parms.add(newBasicNameValuePair("prelt","51")); parms.add(newBasicNameValuePair("returntype","TEXT")); post.setEntity(newUrlEncodedFormEntity(parms)); HttpResponseresp=client.execute(post); //保存请求返回cookie,登录后请求其他页面需要带cookie saveCookie(resp.getAllHeaders(),this.headerCookie); //请求返回链接 JSONObjectjsonObj=JSONObject.parseObject(EntityUtils.toString(resp.getEntity())); this.retcode=jsonObj.getIntValue("retcode"); this.uid=jsonObj.getString("uid"); this.nick=jsonObj.getString("nick"); this.domainurls=jsonObj.getJSONArray("crossDomainUrlList"); List<String>retMsg=newArrayList<String>(); inti=0; for(Objecturl:domainurls){ System.out.println("url:"+url.toString()); get.setURI(newURI(url.toString()+"&callback=sinaSSOController.doCrossDomainCallBack&scriptId=ssoscript"+i+"&client=ssologin.js(v1.4.15)&_="+newDate().getTime())); resp=client.execute(get); retMsg.add(EntityUtils.toString(resp.getEntity())); i++; } Oauthoauth=newOauth(); try{ Stringurl=oauth.authorize("code"); get.setURI(newURI(url)); List<URI>allRedirectLocations=getAllRedirectLocations(url); for(URIuri:allRedirectLocations){ StringretUrl=uri.toString(); intbegin=retUrl.indexOf("code="); if(begin!=-1){ intend=retUrl.indexOf("&",begin); if(end==-1) end=retUrl.length(); Stringcode=retUrl.substring(begin+5,end); if(code!=null){ try{ AccessTokentoken=oauth.getAccessTokenByCode(code); returntoken; }catch(Exceptione){ e.printStackTrace(); } } break; } } }catch(WeiboExceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } returnnull; } publicList<URI>getAllRedirectLocations(Stringlink)throwsClientProtocolException,IOException{ List<URI>redirectLocations=null; CloseableHttpResponseresponse=null; try{ HttpClientContextcontext=HttpClientContext.create(); HttpGethttpGet=newHttpGet(link); //添加请求cookie到请求头 httpGet.addHeader("Cookie",this.headerCookie.toString()); response=(CloseableHttpResponse)client.execute(httpGet,context); //获取所有的重定向位置 redirectLocations=context.getRedirectLocations(); }finally{ if(response!=null){ response.close(); } } returnredirectLocations; } /** *发微博 *@paramtoken认证Token *@paramcontent微博内容 *@return *@throwsException */ publicstaticbooleansinaSendWeibo(Stringtoken,Stringcontent)throwsException{ booleanflag=false; Timelinetm=newTimeline(token); try { Statusstatus=tm.updateStatus(content); flag=true; } catch(WeiboExceptione) { flag=false; System.out.println(e.getErrorCode()); } returnflag; } /** *登录 */ @SuppressWarnings("static-access") publicvoidlogin(Stringcontext){ try{ this.preLogin(); AccessTokenat=this.accountLogin(); this.sinaSendWeibo(at.getAccessToken(),context); }catch(ClientProtocolExceptione){ e.printStackTrace(); }catch(IOExceptione){ e.printStackTrace(); }catch(NoSuchMethodExceptione){ e.printStackTrace(); }catch(ScriptExceptione){ e.printStackTrace(); }catch(URISyntaxExceptione){ e.printStackTrace(); }catch(Exceptione){ //TODOAuto-generatedcatchblock e.printStackTrace(); } } publicHttpClientgetClient(){ returnclient; } publicvoidsetClient(HttpClientclient){ this.client=client; } publicHttpPostgetPost(){ returnpost; } publicvoidsetPost(HttpPostpost){ this.post=post; } publicHttpGetgetGet(){ returnget; } publicvoidsetGet(HttpGetget){ this.get=get; } publicStringgetUsername(){ returnusername; } publicvoidsetUsername(Stringusername){ this.username=username; } publicStringgetSu(){ returnsu; } publicvoidsetSu(Stringsu){ this.su=su; } publicStringgetSp(){ returnsp; } publicvoidsetSp(Stringsp){ this.sp=sp; } publicStringgetNonce(){ returnnonce; } publicvoidsetNonce(Stringnonce){ this.nonce=nonce; } publicStringgetRsakv(){ returnrsakv; } publicvoidsetRsakv(Stringrsakv){ this.rsakv=rsakv; } publicStringgetPubkey(){ returnpubkey; } publicvoidsetPubkey(Stringpubkey){ this.pubkey=pubkey; } publicintgetRetcode(){ returnretcode; } publicvoidsetRetcode(intretcode){ this.retcode=retcode; } publicStringgetUid(){ returnuid; } publicvoidsetUid(Stringuid){ this.uid=uid; } publicStringgetNick(){ returnnick; } publicvoidsetNick(Stringnick){ this.nick=nick; } publicstaticStringgetSina_js(){ returnsina_js; } publicBasicCookieStoregetCookieStore(){ returncookieStore; } publicvoidsetCookieStore(BasicCookieStorecookieStore){ this.cookieStore=cookieStore; } publicstaticvoidmain(String[]args)throwsHttpException,IOException{ newSinaWeiboLogger("微博账号","密码").login("xxxxx"); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。