HttpClient模拟登陆的简单例子_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > HttpClient模拟登陆的简单例子

HttpClient模拟登陆的简单例子

 2014/6/24 18:33:47  NealCai  程序员俱乐部  我要评论(0)
  • 摘要:packagecom;importjava.io.BufferedReader;importjava.io.InputStreamReader;importorg.apache.commons.httpclient.Cookie;importorg.apache.commons.httpclient.HttpClient;importorg.apache.commons.httpclient.NameValuePair;importorg.apache.commons.httpclient
  • 标签:例子 client HTTP
class="java" name="code">package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.PostMethod;

public class FormLoginDemo {
	static final String LOGON_SITE = "127.0.0.1";
	static final int LOGON_PORT = 8080;

	public static void main(String[] args) throws Exception {
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);

		// 模拟登录页面 login.jsp->main.jsp
		PostMethod post = new PostMethod("/prcs/loginAction.do?method=login");
		NameValuePair name = new NameValuePair("userId", "admin");
		NameValuePair pass = new NameValuePair("password", "password");
		NameValuePair sbx = new NameValuePair("Submit.x", "0");
		NameValuePair sby = new NameValuePair("Submit.y", "0");
		NameValuePair sb = new NameValuePair("Submit", "Save");
		post.setRequestBody(new NameValuePair[] { name, pass,sbx,sby,sb });
		int status = client.executeMethod(post);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream()));  
		StringBuffer stringBuffer = new StringBuffer();  
		String str = "";  
		while((str = reader.readLine())!=null){  
		    stringBuffer.append(str);  
		}  
		String ts = stringBuffer.toString();  
		
		
		System.out.println(ts);
		post.releaseConnection();

		// 查看 cookie 信息
		CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
		Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
				client.getState().getCookies());
		if (cookies.length == 0) {
			System.out.println("None");
		} else {
			for (int i = 0; i < cookies.length; i++) {
				System.out.println(cookies[i].toString());
			}
		}

		// 登陆之后访问的页面 main2.jsp
		PostMethod get = new PostMethod("/prcs/productionAction.do?method=prodSearchInit");
		client.executeMethod(get);
		System.out.println(get.getResponseBodyAsString());
		get.releaseConnection();
	}
}


比较要注意的是NameValuePair的参数最好用Firebug或者Fiddler抓取下表单,看下具体的参数。
这是一个最简单的Httpclient的例子,接下来会写一篇过代理并且访问HTTPS的例子。

发表评论
用户名: 匿名