①用Fiddler2追蹤登錄時(shí)的post請(qǐng)求,發(fā)現(xiàn)需要以下參數(shù):
check
uname
backURL
autoLogin
pwd
其中,backURL="/",check=“1”,autoLogin可默認(rèn)為1
于是,只剩
uname和
pwd
②創(chuàng)建一個(gè)HttpClient
private DefaultHttpClient httpclient = new DefaultHttpClient();
③創(chuàng)建一個(gè)
HttpPost
HttpPost httpost = new HttpPost(CommonConst.loginUrl);
④偽裝httpost,騙過(guò)服務(wù)器
/**
* pretend to be a browser quietly
*/
private void setPostHeader(HttpPost post) {
post.setHeader(CommonConst.UserAgent, CommonConst.HttpAgent);
post.setHeader("Origin", CommonConst.weiboUrl);
post.setHeader("Cache-Control", "max-age=0");
post.setHeader("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
post.setHeader("Accept-Encoding", "gzip,deflate,sdch");
post.setHeader("Accept-Language", "en-US,en;q=0.8");
post.setHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
post.setHeader("Accept-Encoding", "gzip,deflate,sdch");
post.setHeader("Referer", CommonConst.loginUrl);
}
⑤創(chuàng)建NameValuePair
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("check", this.check));
nvps.add(new BasicNameValuePair("uname", this.uname));
nvps.add(new BasicNameValuePair("backURL", this.backURL));
nvps.add(new BasicNameValuePair("autoLogin", this.autoLogin));
nvps.add(new BasicNameValuePair("pwd", this.pwd));
⑥用setEntity方法,給httpost設(shè)置相關(guān)參數(shù)
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
⑦向相應(yīng)的host上提交post請(qǐng)求
HttpHost targetHost = new HttpHost(CommonConst.host);
response = httpclient.execute(targetHost, httpost);
login代碼:
private boolean login() {
// httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
HttpPost httpost = new HttpPost(CommonConst.loginUrl);
setPostHeader(httpost);
// All the parameters post to the web site
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("check", this.check));
nvps.add(new BasicNameValuePair("uname", this.uname));
nvps.add(new BasicNameValuePair("backURL", this.backURL));
nvps.add(new BasicNameValuePair("autoLogin", this.autoLogin));
nvps.add(new BasicNameValuePair("pwd", this.pwd));
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpHost targetHost = new HttpHost(CommonConst.host);
response = httpclient.execute(targetHost, httpost);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
httpost.abort();
}
return true;
}
附CommonConst.java
package com.yinger;
public class CommonConst {
public static String HttpAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5";
public static String loginUrl = "http://m.weibo.cn/login";
public static String host = "m.weibo.cn";
public static String weiboUrl = "http://m.weibo.cn";
public static String UserAgent = "User-Agent";
}
posted on 2012-07-11 11:59
Ying-er 閱讀(5241)
評(píng)論(5) 編輯 收藏