`

HttpClient 登陆iteye

    博客分类:
  • java
阅读更多
	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();
	    }
	}
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics