java微博模拟登陆_用httpclient模拟浏览器,登录新浪微博

①用Fiddler2追踪登录时的post请求,发现需要以下参数:

check

uname

backURL

autoLogin

pwd

其中,backURL="/",check=“1”,autoLogin可默认为1

于是,只剩

uname和

pwd

②创建一个HttpClient

privateDefaultHttpClient httpclient=newDefaultHttpClient();

③创建一个

HttpPost

HttpPost httpost=newHttpPost(CommonConst.loginUrl);

④伪装httpost,骗过服务器

/*** pretend to be a browser quietly*/privatevoidsetPostHeader(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);

}

⑤创建NameValuePair

Listnvps=newArrayList();

nvps.add(newBasicNameValuePair("check",this.check));

nvps.add(newBasicNameValuePair("uname",this.uname));

nvps.add(newBasicNameValuePair("backURL",this.backURL));

nvps.add(newBasicNameValuePair("autoLogin",this.autoLogin));

nvps.add(newBasicNameValuePair("pwd",this.pwd));

⑥用setEntity方法,给httpost设置相关参数

httpost.setEntity(newUrlEncodedFormEntity(nvps, HTTP.UTF_8));

⑦向相应的host上提交post请求

HttpHost targetHost=newHttpHost(CommonConst.host);

response=httpclient.execute(targetHost, httpost);

login代码:

privatebooleanlogin() {//httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);HttpPost httpost=newHttpPost(CommonConst.loginUrl);

setPostHeader(httpost);//All the parameters post to the web siteListnvps=newArrayList();

nvps.add(newBasicNameValuePair("check",this.check));

nvps.add(newBasicNameValuePair("uname",this.uname));

nvps.add(newBasicNameValuePair("backURL",this.backURL));

nvps.add(newBasicNameValuePair("autoLogin",this.autoLogin));

nvps.add(newBasicNameValuePair("pwd",this.pwd));try{

httpost.setEntity(newUrlEncodedFormEntity(nvps, HTTP.UTF_8));

HttpHost targetHost=newHttpHost(CommonConst.host);

response=httpclient.execute(targetHost, httpost);

}catch(Exception e) {

e.printStackTrace();returnfalse;

}finally{

httpost.abort();

}returntrue;

}

附CommonConst.java

packagecom.yinger;publicclassCommonConst {publicstaticString 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";publicstaticString loginUrl="http://m.weibo.cn/login";publicstaticString host="m.weibo.cn";publicstaticString weiboUrl="http://m.weibo.cn";publicstaticString UserAgent="User-Agent";}

posted on 2012-07-11 11:59 Ying-er 阅读(5020) 评论(5)  编辑  收藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值