HttpClient模拟登陆

httpclient登录新浪微博(非SDK方式)

分享此文章

苦逼的折腾了快一星期,总算把新浪微博rsa加密登录折腾ok了,这里需要注意的是httpclient最好用4.0的,否则cookie管理很是问题。

进入正题,最近新浪微博更新了sso登录方式,加密算法变成了rsa,获取nonce和servertime,pubkey,这里涉及到rsa加密,通常用java进行rsa加密一般都是从文件读取公钥信息或者是base64编码的公钥信息转换成key,然后进行加密,但是新浪给的不是base64加密,而是给的一个N(参见RSA加密算法,RSA加密算法),而我先入为主,把新浪给的pubkey当作base64编码的公钥信息,苦逼的折腾了快一天。后来再细看看RSA加密算法感觉pubkey不像是base64编码,看到网上有人分析新浪的sso.js,于是我也看一下,终于有收获,看到他把pubkey解析成biginteger,感觉怪怪的,联想到rsa的百科,发现应该是我搞错了,遂找到以下方法。用pubkey进行加密。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

public String rsaCrypt ( String modeHex , String exponentHex , String messageg ) throws IllegalBlockSizeException ,
             BadPaddingException , NoSuchAlgorithmException ,
             InvalidKeySpecException , NoSuchPaddingException ,
             InvalidKeyException , UnsupportedEncodingException {
         KeyFactory factory = KeyFactory . getInstance ( "RSA" ) ;
         BigInteger m = new BigInteger ( modeHex , 16 ) ; /* public exponent */
         BigInteger e = new BigInteger ( exponentHex , 16 ) ; /* modulus */
         RSAPublicKeySpec spec = new RSAPublicKeySpec ( m , e ) ;
         RSAPublicKey pub = ( RSAPublicKey ) factory . generatePublic ( spec ) ;
         Cipher enc = Cipher . getInstance ( "RSA" ) ;
         enc . init ( Cipher . ENCRYPT_MODE , pub ) ;
         byte [ ] encryptedContentKey = enc . doFinal ( messageg . getBytes ( "GB2312" ) ) ;
         return new String ( Hex . encodeHex ( encryptedContentKey ) ) ;
     }

方法名气得不是很理想,但是不影响我们学习。搞定加密了,接下来更苦逼的是http-client3这托,我看网上有人弄出来的代码,参考着弄下,但是他们的验证方法,参数都有问题,我参照有人用ruby写的(sso 1.4.2版本的),将该替换的都替换了,一直进行到ajaxlogin这里,可以获取到我的个人信息,但是苦逼的是,真正登录的时候不行,我怀疑是cookie问题,因为一直警告我cookie reject,因为新浪sso登录时候用了些技巧解决跨域。好,那我就山寨点,把cookie domain该了,改成.weibo.com最终获取用户主页时retcode=6102,查了下sso.js代码,发现是没登录成功 ,cookie问题。什么办法读想了,抓包,分析,firebug分析,google了无数遍,最后还是没成功。无奈继续google,苦心不负有心人,最终发现这篇,http-client4来做的,我隐约记得官方推荐用hc4,于是就搞了下,竟然可以获得首页一些信息,虽然不是html的,但应该是成功了,之前没成功的话获取个人主页会得到登录的html。下面是主要代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

import java . io . IOException ;
import java . security . InvalidKeyException ;
import java . security . NoSuchAlgorithmException ;
import java . security . spec . InvalidKeySpecException ;
import java . util . ArrayList ;
import java . util . Date ;
import java . util . List ;
import javax . crypto . BadPaddingException ;
import javax . crypto . IllegalBlockSizeException ;
import javax . crypto . NoSuchPaddingException ;
import org . apache . commons . codec . binary . Base64 ;
import org . apache . commons . logging . Log ;
import org . apache . commons . logging . LogFactory ;
import org . apache . http . NameValuePair ;
import org . apache . http . HttpException ;
import org . apache . http . HttpResponse ;
import org . apache . http . ParseException ;
import org . apache . http . client . HttpClient ;
import org . apache . http . client . entity . UrlEncodedFormEntity ;
import org . apache . http . client . methods . HttpGet ;
import org . apache . http . client . methods . HttpPost ;
import org . apache . http . client . params . CookiePolicy ;
import org . apache . http . impl . client . DefaultHttpClient ;
import org . apache . http . message . BasicNameValuePair ;
import org . apache . http . params . HttpConnectionParams ;
import org . apache . http . protocol . HTTP ;
import org . apache . http . util . EntityUtils ;
import org . json . JSONException ;
import org . json . JSONObject ;
public class Main {
     static String SINA_PK = "EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D24"
             + "5A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915F6D63C55FE2F08A49B353F444AD39"
             + "93CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE"
             + "1F6739884B9777E4FE9E88A1BBE495927AC4A799B3181D6442443" ;
     static String username = "用户名" ;
     static String passwd = "密码" ;
     private static final Log logger = LogFactory . getLog ( Main . class ) ;
     public static void main ( String [ ] args ) throws HttpException , IOException ,
             JSONException , InvalidKeyException , IllegalBlockSizeException , BadPaddingException , NoSuchAlgorithmException , InvalidKeySpecException , NoSuchPaddingException {
         DefaultHttpClient client = new DefaultHttpClient ( ) ;
         client . getParams ( ) . setParameter ( "http.protocol.cookie-policy" ,
                 CookiePolicy . BROWSER_COMPATIBILITY ) ;
         client . getParams ( ) . setParameter (
                 HttpConnectionParams . CONNECTION_TIMEOUT , 5000 ) ;
         HttpPost post = new HttpPost (
                 "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.2)" ) ;
         PreLoginInfo info = getPreLoginBean ( client ) ;
         long servertime = info . servertime ;
         String nonce = info . nonce ;
         String pwdString = servertime + "\t" + nonce + "\n" + "HMC123$%^" ;
         String sp = new BigIntegerRSA ( ) . rsaCrypt ( SINA_PK , "10001" , pwdString ) ;
         List < NameValuePair > nvps = new ArrayList < NameValuePair > ( ) ;
         nvps . add ( new BasicNameValuePair ( "entry" , "weibo" ) ) ;
         nvps . add ( new BasicNameValuePair ( "gateway" , "1" ) ) ;
         nvps . add ( new BasicNameValuePair ( "from" , "" ) ) ;
         nvps . add ( new BasicNameValuePair ( "savestate" , "7" ) ) ;
         nvps . add ( new BasicNameValuePair ( "useticket" , "1" ) ) ;
         nvps . add ( new BasicNameValuePair ( "ssosimplelogin" , "1" ) ) ;
         nvps . add ( new BasicNameValuePair ( "vsnf" , "1" ) ) ;
         // new NameValuePair("vsnval", ""),
         nvps . add ( new BasicNameValuePair ( "su" , encodeUserName ( username ) ) ) ;
         nvps . add ( new BasicNameValuePair ( "service" , "miniblog" ) ) ;
         nvps . add ( new BasicNameValuePair ( "servertime" , servertime + "" ) ) ;
         nvps . add ( new BasicNameValuePair ( "nonce" , nonce ) ) ;
         nvps . add ( new BasicNameValuePair ( "pwencode" , "rsa2" ) ) ;
         nvps . add ( new BasicNameValuePair ( "rsakv" , info . rsakv ) ) ;
         nvps . add ( new BasicNameValuePair ( "sp" , sp ) ) ;
         nvps . add ( new BasicNameValuePair ( "encoding" , "UTF-8" ) ) ;
         nvps . add ( new BasicNameValuePair ( "prelt" , "115" ) ) ;
         nvps . add ( new BasicNameValuePair ( "returntype" , "META" ) ) ;
         nvps . add ( new BasicNameValuePair (
                 "url" ,
                 "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack" ) ) ;
         post . setEntity ( new UrlEncodedFormEntity ( nvps , HTTP . UTF_8 ) ) ;
         HttpResponse response = client . execute ( post ) ;   
         String entity = EntityUtils . toString ( response . getEntity ( ) ) ;   
         String url = entity . substring ( entity   
                 . indexOf ( "http://weibo.com/ajaxlogin.php?" ) , entity   
                 . indexOf ( "code=0" ) + 6 ) ;
         logger . debug ( "url:" + url ) ;
     // 获取到实际url进行连接  
         HttpGet getMethod = new HttpGet ( url ) ;   
         response = client . execute ( getMethod ) ;   
         entity = EntityUtils . toString ( response . getEntity ( ) ) ;   
         entity = entity . substring ( entity . indexOf ( "userdomain" ) + 13 , entity   
                 . lastIndexOf ( "\" "));  
        logger.debug(entity);  
        getMethod = new HttpGet(" http : //weibo.com/humingchun?wvr=5&lf=reg");  
         response = client . execute ( getMethod ) ;   
         entity = EntityUtils . toString ( response . getEntity ( ) ) ;   
         // Document doc =  
         // Jsoup.parse(EntityUtils.toString(response.getEntity()));  
         System . out . println ( entity ) ;
         logger . debug ( entity ) ;
     }
     private static PreLoginInfo getPreLoginBean ( HttpClient client )
             throws HttpException , IOException , JSONException {
         String serverTime = getPreLoginInfo ( client ) ;
         System . out . println ( "" ) ;
         JSONObject jsonInfo = new JSONObject ( serverTime ) ;
         PreLoginInfo info = new PreLoginInfo ( ) ;
         info . nonce = jsonInfo . getString ( "nonce" ) ;
         info . pcid = jsonInfo . getString ( "pcid" ) ;
         info . pubkey = jsonInfo . getString ( "pubkey" ) ;
         info . retcode = jsonInfo . getInt ( "retcode" ) ;
         info . rsakv = jsonInfo . getString ( "rsakv" ) ;
         info . servertime = jsonInfo . getLong ( "servertime" ) ;
         return info ;
     }
     public static String getPreLoginInfo ( HttpClient client )
             throws ParseException , IOException {
         String preloginurl = "http://login.sina.com.cn/sso/prelogin.php?entry=sso&"
                 + "callback=sinaSSOController.preloginCallBack&su="
                 + "dW5kZWZpbmVk"
                 + "&rsakt=mod&client=ssologin.js(v1.4.2)"
                 + "&_=" + getCurrentTime ( ) ;
         HttpGet get = new HttpGet ( preloginurl ) ;
         HttpResponse response = client . execute ( get ) ;
         String getResp = EntityUtils . toString ( response . getEntity ( ) ) ;
         int firstLeftBracket = getResp . indexOf ( "(" ) ;
         int lastRightBracket = getResp . lastIndexOf ( ")" ) ;
         String jsonBody = getResp . substring ( firstLeftBracket + 1 ,
                 lastRightBracket ) ;
         System . out . println ( jsonBody ) ;
         return jsonBody ;
     }
     private static String getCurrentTime ( ) {
         long servertime = new Date ( ) . getTime ( ) / 1000 ;
         return String . valueOf ( servertime ) ;
     }
     private static String encodeUserName ( String email ) {
         email = email . replaceFirst ( "@" , "%40" ) ; // MzM3MjQwNTUyJTQwcXEuY29t
         email = Base64 . encodeBase64String ( email . getBytes ( ) ) ;
         return email ;
     }
}

测试过的代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;/*** 使用httpclient4登陆百度* @author gohands**/
public class BaiduLogin {private static String URL_CHARACTER = "gb2312"; // 统一字符集/*** @param args*/public static void main(String[] args) throws Exception {//初始化DefaultHttpClient httpclient = new DefaultHttpClient();// 这一行必须要加,否则服务器无法获取登陆状态HttpClientParams.setCookiePolicy(httpclient.getParams(),CookiePolicy.BROWSER_COMPATIBILITY);// 第一次访问String url = "http://www.baidu.com";HttpGet httpget = new HttpGet(url);HttpResponse response = httpclient.execute(httpget);System.out.println("Length1::" + response.getEntity().getContentLength());HttpEntity entity = response.getEntity();BaiduLogin.printEntity(entity);// 登陆【使用POST方式登录】// 如果要直接执行,麻烦去申请个百度的帐号// 不好意思,给百度做广告了HttpPost httpost = new HttpPost("https://passport.baidu.com/v2/api/?login");List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("username", "dollar625"));nvps.add(new BasicNameValuePair("password", "********"));httpost.setEntity(new UrlEncodedFormEntity(nvps, BaiduLogin.URL_CHARACTER));response = httpclient.execute(httpost);// 第二次访问System.out.println("\n----------------------------------------");System.out.println(response.getStatusLine());List<Cookie> cookies = httpclient.getCookieStore().getCookies();entity = response.getEntity();BaiduLogin.printEntity(entity);System.out.println("\n----------------------------------------");cookies = httpclient.getCookieStore().getCookies();System.out.println("cookies" + cookies.size());httpget = new HttpGet(url);// httpget.setr// httpget.setHeader(name, value)response = httpclient.execute(httpget);System.out.println("Length2::"+ response.getEntity().getContentLength());entity = response.getEntity();BaiduLogin.printEntity(entity);}/*** 输出entity内容,获取和输出返回的HTML文* @param entity* @throws IllegalStateException* @throws IOException*/private static void printEntity(HttpEntity entity)throws IllegalStateException, IOException {if (entity == null) {return;}System.out.println("HttpEntity start >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");System.out.println("Response content length: " + entity.getContentLength());InputStream is = entity.getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));List<Byte> li = new ArrayList();int i;//之所以写的如此复杂是因为了解决中文问题while ((i = is.read()) != -1) {li.add((byte) i);}byte a[] = new byte[li.size()];for (i = 0; i < a.length; i++) {a[i] = (byte) li.get(i);}System.out.println(new String(a, BaiduLogin.URL_CHARACTER)); // 打印HTML内容entity.consumeContent(); // entity销毁System.out.println("HttpEntity END >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");}
}

  得到的结果:

Length1::10299
HttpEntity start >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Response content length: 10299
<!DOCTYPE html><!--STATUS OK-->    <html><head>  <meta http-equiv="content-type" content="text/html;charset=utf-8">  <title>?惧害涓??锛??灏辩???/title> <style >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden}#ftConw{width:720px;margin:0 auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{color:#999;padding:4px 10px 5px 0;text-align:right}#u a{margin:0 5px}#u .reg{margin:0}#m{width:720px;margin:0 auto}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:110px;text-align:left;z-index:1}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px}.s_ipt_wr{width:418px;height:30px;display:inline-block;margin-right:5px;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png) no-repeat -304px 0;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:0;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background:#ddd url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png);cursor:pointer}.s_btn_h{background-position:-100px 0}.s_btn_wr{width:97px;height:34px;display:inline-block;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png) no-repeat -202px 0;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "瀹??"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0 18px 0 0;background:url(http://s1.bdstatic.com/r/www/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px 1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter:progid:DXImageTransform.Microsoft.Shadow(Strength=2,Direction=135,Color="#cccccc")\9}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp a{color:#666}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none}#sekj{margin-left:14px}#shouji{margin-right:14px}</style> <script>function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('http://www.baidu.com/');}</script></head><body>  <div id="wrapper"><div id="content"> <div id="u"><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_setting">??储璁剧疆</a>|<a href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" οnclick="return false;">?诲?</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" target="_blank" name="tj_reg" class="reg">娉ㄥ?</a></div> <div id="m"> <p id="lg"><img src="http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif" width="270" height="129"   ></p> <p id="nv"><a href="http://news.baidu.com">??nbsp;??/a>??b>缃?nbsp;椤?/b>??a href="http://tieba.baidu.com">璐?nbsp;??/a>??a href="http://zhidao.baidu.com">??nbsp;??/a>??a href="http://music.baidu.com">??nbsp;涔?/a>??a href="http://image.baidu.com">??nbsp;??/a>??a href="http://video.baidu.com">瑙?nbsp;棰?/a>??a href="http://map.baidu.com">??nbsp;??/a></p><div id="fm"><form name="f" action="/s"><span class="s_ipt_wr"><input type="text" name="wd" id="kw" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="utf-8"><span class="s_btn_wr"><input type="submit" value="?惧害涓??" id="su" class="s_btn" οnmοusedοwn="this.className='s_btn s_btn_h'" οnmοuseοut="this.className='s_btn'"></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>杈??娉?/span></div></span></span><ul id="mMenu"><li><a href="#" name="ime_hw">???</a></li><li><a href="#" name="ime_py">?奸?</a></li><li class="ln"></li><li><a href="#" name="ime_cl">?抽?</a></li></ul></div> <p id="lk"><a href="http://baike.baidu.com">?剧?</a>??a href="http://wenku.baidu.com">???</a>??a href="http://www.hao123.com">hao123</a><span> | <a href="http://www.baidu.com/more/">?村?>></a></span></p><p id="lm"></p> </div> </div> <div id="ftCon"><div id="ftConw"> <p ><a id="seth" onClick="h(this)" href="/" οnmοusedοwn="return ns_c({'fm':'behs','tab':'homepage','pos':0})">???搴??涓轰富椤?/a><a id="setf" href="http://www.baidu.com/cache/sethelp/index.html" οnmοusedοwn="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">???搴??涓轰富椤?/a><span id="sekj"><a href="http://liulanqi.baidu.com/ps.php" target="_blank" οnmοusedοwn="return ns_c({'fm':'behs','tab':'bdbrwlk','pos':1})">瀹???惧害娴????/a></span></p><p id="lh"><a href="http://e.baidu.com/?refer=888" οnmοusedοwn="return ns_c({'fm':'behs','tab':'btlink','pos':2})">????惧害?ㄥ箍</a> | <a href="http://top.baidu.com">??储椋??姒?/a> | <a href="http://home.baidu.com">?充??惧害</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">©2013 Baidu <a href="/duty/">浣跨??惧害???璇?/a> <a href="http://www.miibeian.gov.cn" target="_blank">浜?CP璇?30173??/a> <img src="http://www.baidu.com/cache/global/img/gs.gif"></p></div></div> </div> </body><script>var bds={se:{},comm : {ishome : 1,sid : "1464_1945_1788",user : "",username : "",sugHost : "http://suggestion.baidu.com/su",personalData : "",loginAction : []}}</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/global/js/home-2.8.js" charset="gbk"></script><script>var bdUser = null;var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();if(n.cookieEnabled){bds.se.sug();};function addEV(o, e, f){if(w.attachEvent){o.attachEvent("on" + e, f);}else if(w.addEventListener){ o.addEventListener(e, f, false);}}function G(id){return d.getElementById(id);}function ns_c(q){var p = encodeURIComponent(window.document.location.href), sQ = '', sV = '', mu='', img = window["BD_PS_C" + (new Date()).getTime()] = new Image();for (v in q) {sV = q[v];sQ += v + "=" + sV + "&";} mu= "&mu=" + p ;img.src = "http://nsclick.baidu.com/v.gif?pid=201&pj=www&rsv_sid=1464_1945_1788&" + sQ + "path="+p+"&t="+new Date().getTime();return true;}if(/\bbdime=[12]/.test(d.cookie)){document.write('<script src=http://s1.bdstatic.com/r/www/cache/ime/js/openime-1.0.1.js charset="gbk"><\/script>');}(function(){var u = G("u").getElementsByTagName("a"), nv = G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un = "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk = ["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.event;var target = e.target || e.srcElement;ns_c({'fm':'behs','tab':target.name||'tj_user','un':encodeURIComponent(un)});});}for(var i = 0; i < u.length; i++){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i];}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(function() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn=20&ct=1&ie=utf-8'],'tj_tieba': ['kw', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk')],kw = G('kw');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURIComponent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();addEV(w,"load",function(){k.focus()});w.οnunlοad=function(){};</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/global/js/tangram-1.3.4c1.0.js"></script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/user/js/u-1.3.4.js" charset="gbk"></script><script>try{document.cookie="WWW_ST=;expires=Sat, 01 Jan 2000 00:00:00 GMT";baidu.on(document.forms[0],"submit",function(){var _t=new Date().getTime();document.cookie = "WWW_ST=" + _t +";expires=" + new Date(_t + 10000).toGMTString()})}catch(e){}</script></html><!--3847f41d362754ab-->
HttpEntity END >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>----------------------------------------
HTTP/1.1 200 OK
HttpEntity start >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Response content length: 439
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body><script type="text/javascript">var url = encodeURI('https://passport.baidu.com/jump.html?error=119998&callback=&index=0&username=&phonenumber=&mail=&tpl=&u=https%3A%2F%2Fpassport.baidu.com%2F&needToModifyPassword=0&gotourl=');
//parent.callback(url)
window.location.replace(url);</script>
</body>
</html>
HttpEntity END >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>----------------------------------------
cookies2
Length2::10309
HttpEntity start >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Response content length: 10309
<!DOCTYPE html><!--STATUS OK-->    <html><head>  <meta http-equiv="content-type" content="text/html;charset=utf-8">  <title>?惧害涓??锛??灏辩???/title> <style >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden}#ftConw{width:720px;margin:0 auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td{text-align:left}img{border:0}a{color:#00c}a:active{color:#f60}#u{color:#999;padding:4px 10px 5px 0;text-align:right}#u a{margin:0 5px}#u .reg{margin:0}#m{width:720px;margin:0 auto}#nv a,#nv b,.btn,#lk{font-size:14px}#fm{padding-left:110px;text-align:left;z-index:1}input{border:0;padding:0}#nv{height:19px;font-size:16px;margin:0 0 4px;text-align:left;text-indent:137px}.s_ipt_wr{width:418px;height:30px;display:inline-block;margin-right:5px;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png) no-repeat -304px 0;border:1px solid #b6b6b6;border-color:#9a9a9a #cdcdcd #cdcdcd #9a9a9a;vertical-align:top}.s_ipt{width:405px;height:22px;font:16px/22px arial;margin:5px 0 0 7px;background:#fff;outline:0;-webkit-appearance:none}.s_btn{width:95px;height:32px;padding-top:2px\9;font-size:14px;background:#ddd url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png);cursor:pointer}.s_btn_h{background-position:-100px 0}.s_btn_wr{width:97px;height:34px;display:inline-block;background:url(http://s1.bdstatic.com/r/www/img/i-1.0.0.png) no-repeat -202px 0;*position:relative;z-index:0;vertical-align:top}#lg img{vertical-align:top;margin-bottom:3px}#lk{margin:33px 0}#lk span{font:14px "瀹??"}#lm{height:60px}#lh{margin:16px 0 5px;word-spacing:3px}.tools{position:absolute;top:-4px;*top:10px;right:7px}#mHolder{width:62px;position:relative;z-index:296;display:none}#mCon{height:18px;line-height:18px;position:absolute;cursor:pointer;padding:0 18px 0 0;background:url(http://s1.bdstatic.com/r/www/img/bg-1.0.0.gif) no-repeat right -134px;background-position:right -136px\9}#mCon span{color:#00c;cursor:default;display:block}#mCon .hw{text-decoration:underline;cursor:pointer}#mMenu a{width:100%;height:100%;display:block;line-height:22px;text-indent:6px;text-decoration:none;filter:none\9}#mMenu,#user ul{box-shadow:1px 1px 2px #ccc;-moz-box-shadow:1px 1px 2px #ccc;-webkit-box-shadow:1px 1px 2px #ccc;filter:progid:DXImageTransform.Microsoft.Shadow(Strength=2,Direction=135,Color="#cccccc")\9}#mMenu{width:56px;border:1px solid #9b9b9b;list-style:none;position:absolute;right:27px;top:28px;display:none;background:#fff}#mMenu a:hover{background:#ebebeb}#mMenu .ln{height:1px;background:#ebebeb;overflow:hidden;font-size:1px;line-height:1px;margin-top:-1px}#cp,#cp a{color:#666}#seth{display:none;behavior:url(#default#homepage)}#setf{display:none}#sekj{margin-left:14px}#shouji{margin-right:14px}</style> <script>function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('http://www.baidu.com/');}</script></head><body>  <div id="wrapper"><div id="content"> <div id="u"><a href="http://www.baidu.com/gaoji/preferences.html" name="tj_setting">??储璁剧疆</a>|<a href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" οnclick="return false;">?诲?</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" target="_blank" name="tj_reg" class="reg">娉ㄥ?</a></div> <div id="m"> <p id="lg"><img src="http://www.baidu.com/img/shouye_b5486898c692066bd2cbaeda86d74448.gif" width="270" height="129"   ></p> <p id="nv"><a href="http://news.baidu.com">??nbsp;??/a>??b>缃?nbsp;椤?/b>??a href="http://tieba.baidu.com">璐?nbsp;??/a>??a href="http://zhidao.baidu.com">??nbsp;??/a>??a href="http://music.baidu.com">??nbsp;涔?/a>??a href="http://image.baidu.com">??nbsp;??/a>??a href="http://video.baidu.com">瑙?nbsp;棰?/a>??a href="http://map.baidu.com">??nbsp;??/a></p><div id="fm"><form name="f" action="/s"><span class="s_ipt_wr"><input type="text" name="wd" id="kw" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="utf-8"><span class="s_btn_wr"><input type="submit" value="?惧害涓??" id="su" class="s_btn" οnmοusedοwn="this.className='s_btn s_btn_h'" οnmοuseοut="this.className='s_btn'"></span></form><span class="tools"><span id="mHolder"><div id="mCon"><span>杈??娉?/span></div></span></span><ul id="mMenu"><li><a href="#" name="ime_hw">???</a></li><li><a href="#" name="ime_py">?奸?</a></li><li class="ln"></li><li><a href="#" name="ime_cl">?抽?</a></li></ul></div> <p id="lk"><a href="http://baike.baidu.com">?剧?</a>??a href="http://wenku.baidu.com">???</a>??a href="http://www.hao123.com">hao123</a><span> | <a href="http://www.baidu.com/more/">?村?>></a></span></p><p id="lm"></p> </div> </div> <div id="ftCon"><div id="ftConw"> <p ><a id="seth" onClick="h(this)" href="/" οnmοusedοwn="return ns_c({'fm':'behs','tab':'homepage','pos':0})">???搴??涓轰富椤?/a><a id="setf" href="http://www.baidu.com/cache/sethelp/index.html" οnmοusedοwn="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">???搴??涓轰富椤?/a><span id="sekj"><a href="http://liulanqi.baidu.com/ps.php" target="_blank" οnmοusedοwn="return ns_c({'fm':'behs','tab':'bdbrwlk','pos':1})">瀹???惧害娴????/a></span></p><p id="lh"><a href="http://e.baidu.com/?refer=888" οnmοusedοwn="return ns_c({'fm':'behs','tab':'btlink','pos':2})">????惧害?ㄥ箍</a> | <a href="http://top.baidu.com">??储椋??姒?/a> | <a href="http://home.baidu.com">?充??惧害</a> | <a href="http://ir.baidu.com">About Baidu</a></p><p id="cp">©2013 Baidu <a href="/duty/">浣跨??惧害???璇?/a> <a href="http://www.miibeian.gov.cn" target="_blank">浜?CP璇?30173??/a> <img src="http://www.baidu.com/cache/global/img/gs.gif"></p></div></div> </div> </body><script>var bds={se:{},comm : {ishome : 1,sid : "1452_2043_1945_1788",user : "",username : "",sugHost : "http://suggestion.baidu.com/su",personalData : "",loginAction : []}}</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/global/js/home-2.8.js" charset="gbk"></script><script>var bdUser = null;var w=window,d=document,n=navigator,k=d.f.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();if(n.cookieEnabled){bds.se.sug();};function addEV(o, e, f){if(w.attachEvent){o.attachEvent("on" + e, f);}else if(w.addEventListener){ o.addEventListener(e, f, false);}}function G(id){return d.getElementById(id);}function ns_c(q){var p = encodeURIComponent(window.document.location.href), sQ = '', sV = '', mu='', img = window["BD_PS_C" + (new Date()).getTime()] = new Image();for (v in q) {sV = q[v];sQ += v + "=" + sV + "&";} mu= "&mu=" + p ;img.src = "http://nsclick.baidu.com/v.gif?pid=201&pj=www&rsv_sid=1452_2043_1945_1788&" + sQ + "path="+p+"&t="+new Date().getTime();return true;}if(/\bbdime=[12]/.test(d.cookie)){document.write('<script src=http://s1.bdstatic.com/r/www/cache/ime/js/openime-1.0.1.js charset="gbk"><\/script>');}(function(){var u = G("u").getElementsByTagName("a"), nv = G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un = "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk = ["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.event;var target = e.target || e.srcElement;ns_c({'fm':'behs','tab':target.name||'tj_user','un':encodeURIComponent(un)});});}for(var i = 0; i < u.length; i++){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i];}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(function() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn=20&ct=1&ie=utf-8'],'tj_tieba': ['kw', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk')],kw = G('kw');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURIComponent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();addEV(w,"load",function(){k.focus()});w.οnunlοad=function(){};</script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/global/js/tangram-1.3.4c1.0.js"></script><script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/user/js/u-1.3.4.js" charset="gbk"></script><script>try{document.cookie="WWW_ST=;expires=Sat, 01 Jan 2000 00:00:00 GMT";baidu.on(document.forms[0],"submit",function(){var _t=new Date().getTime();document.cookie = "WWW_ST=" + _t +";expires=" + new Date(_t + 10000).toGMTString()})}catch(e){}</script></html><!--0ba9a2d5f1bcb341-->
HttpEntity END >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

  

http://bbs.csdn.net/topics/370158939

posted on 2013-03-11 23:13  赵乐ACM 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dollarzhaole/archive/2013/03/11/2954836.html

HttpClient模拟登陆相关推荐

  1. 使用HttpClient模拟登陆并爬取网页

    在使用Java进行网页爬虫时经常需要携带登陆的 Cookie 信息,然而 Cookie 是有时效性的,所以经常会碰到 Cookie 失效的情况.如何在 Cookie 失效后自动重新获取成了爬虫急需解决 ...

  2. httpclient模拟登陆微博问题

    我用httpclient模拟登陆微博报如下错误: [DEBUG] RequestAddCookies - Cookie [version: 0][name: USRHAWB][value: usrmd ...

  3. Java--使用httpClient模拟登陆正方教务系统获取课表

    最近形如课程格子与超表课程表应用如雨后春笋般涌现,他们自动获取课程表是怎么实现的呢.于是我用Java实现了一下模拟登陆正方教务系统获取课表的过程. 首先,我们先了解一下网站登录的原理:当我们输入学号, ...

  4. 使用Httpclient模拟登陆正方软件股份有限公司开发的教务管理系统

    事先声明,我写这篇,只是为了分享一下,登录网站不止有使用cookies这一种方法,还有一种使用随机码的方法,并没有泄露"商业机密"的想法,本人才疏学浅,只是在站在巨人的肩膀上,摘到 ...

  5. 2019/1/6 初探JAVA京东 httpclient 模拟登陆(初篇)

    简述:(PS:  大神勿喷,接触爬虫较少) 最近与朋友聊天,关于京东上的业务,遇到某些烦恼,故有此需求,次需求针对性较强,翻来覆去也查阅不少资料. 分析细节 1. 京东账号分为,普通账户,企业账户,专 ...

  6. HTTPClient模拟登陆人人网

    目的: 使用HTTPClient4.0.1登录到人人网,并从特定的网页抓取数据. 总结&注意事项: HttpClient(DefaultHttpClient)代表了一个会话,在同一个会话中,H ...

  7. java使用httpclient简单模拟登陆微信公众开放平台

    注意:本文使用的不是微信公众平台的api,只是采用的模拟登陆的方式. 微信公众账号平台地址:https://mp.weixin.qq.com/ 1 分析登陆信息,获取url 使用谷歌浏览器打开http ...

  8. 豆瓣网络爬虫-java网络爬虫[验证码模拟登陆]详细介绍

    目录 抓包介绍 解决验证码的思路 验证码地址拼接 爬虫实战 爬虫架构 model main 解析htmlparse 数据库操作程序db 近期,有人将本人博客,复制下来,直接上传到百度文库等平台. 本文 ...

  9. 网络爬虫模拟登陆获取数据并解析实战(二)

    本文为原创博客,仅供学习使用.未经本人允许禁止复制下来,上传到百度文库等平台. 目录 分析要获取的数据 程序的结构 构建封装数据的model 模拟登陆程序并解析数据 结果展示 分析要获取的数据 下面继 ...

最新文章

  1. 干货|TensorFlow开发环境搭建(Ubuntu16.04+GPU+TensorFlow源码编译)
  2. SpringBoot报错:Could not autowire. No beans of ‘DiscussantMapper‘ type found
  3. PHP ServerPush (推送) 技术的探讨
  4. 在ubuntu中使用MYBASE
  5. zabbix3.4.4 监控系统安装部署
  6. dart js转换_基于dart生态的FaaS前端一体化建设
  7. 系统架构----(1) 负载均衡
  8. 我们先来了解下什么是网络爬虫?
  9. play ---------idea
  10. css实现背景全透明样式
  11. ghost之后仍然中病毒----与病毒的斗争
  12. HTML5课题意义,毕业论文选题的意义万能套话
  13. 确定不看看我的扫雷吗(C语言)
  14. 找出阿里云RDS数据库的IP地址
  15. esayExcel 获取值 null 去除excel中换行 回车 水平制表符
  16. 怎样开发鸿蒙系统的输入法,2020华为开发者大会 讯飞输入法携手鸿蒙共创未来...
  17. Minecraft Java版
  18. 深度学习和大数据之间,主要是什么关系?
  19. 查看软件版本的cmd命令
  20. VC++游戏编程----游戏画面特效制作1

热门文章

  1. oracle同义词truncate,oracle同义词
  2. IDEA如何将Git回退到某个版本
  3. 279. 自然数拆分 完全背包问题
  4. iOS判断iPhone是否越狱
  5. 计算机管理任务计划程序损坏,win7旗舰版的任务计划程序崩溃了,怎么处理?
  6. 一个极简、高效的秒杀系统-战术实践篇(内附源码)
  7. [从零开始]Flask+Nginx在云服务器上部署服务
  8. 已知 方程 用 matlab 求表达式,已知自变量,因变量和函数表达式,可以用matlab求出函数表达式中的未知参数吗...
  9. MySQL主从复制简介
  10. Mybatis之@SelectKey注解