HttpClient 登陆iteye

	static String cookie;
static String url ="http://www.iteye.com/login";
static String name="xxx";
static String password ="xxx";
public static void main(String[] args) throws Exception{
//keep http connection execute in same httpclient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse resp = httpClient.execute(get);
cookie = resp.getFirstHeader("Set-Cookie").getValue();
HttpEntity e = resp.getEntity();
String r =EntityUtils.toString(e,"gbk");

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("authenticity_token", getToken(r)));
postMethod(params, httpClient);
}

static String getToken(String html){
//解析下返回内容,获取登陆必须的token参数
Document doc = Jsoup.parse(html);
Element ef = doc.getElementById("login_form");
Elements einputs = ef.getElementsByTag("input");
for(Element e : einputs){
if(e.attr("name").equals("authenticity_token")){
return e.attr("value");
}
}
return "";
}
public static void postMethod(List<NameValuePair> params, HttpClient httpClient) throws Exception, IOException{
HttpPost post = new HttpPost(url);
/*
* 没用到
* post.setHeader("Host", "www.iteye.com");
post.setHeader("Origin", "http://www.iteye.com");
post.setHeader("Referer", "http://www.iteye.com/login");
post.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36");
post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8");
post.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
post.setHeader("Cache-Control", "max-age=0");
post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setHeader("Cookie", cookie);*/

post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status==HttpStatus.SC_MOVED_PERMANENTLY || status==HttpStatus.SC_MOVED_TEMPORARILY){//redirect
post.releaseConnection();
String location = response.getFirstHeader("location").getValue();
HttpPost redirectPost = new HttpPost(location);
HttpResponse resp = httpClient.execute(redirectPost);
HttpEntity entity = resp.getEntity();
System.out.println(resp.getFirstHeader("Set-Cookie").getValue());
String result =EntityUtils.toString(entity,"gbk");
//登陆后返回首页内容,若想进一步获取内容,可以继续解析返回内容
System.out.println(result);
redirectPost.releaseConnection();
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值