package com.test;
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.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class FormLoginDemo {
static final String LOGON_STR = "localhost";
static final int LOGON_PORT = 8080;
public static void main(String[] args) throws Exception{
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_STR, LOGON_PORT);
// 模拟登录页面login.jsp->main.jsp
PostMethod post = new PostMethod("/a.jsp");
NameValuePair name = new NameValuePair("name", "Id");
NameValuePair pass = new NameValuePair("password" , "Id");
post.setRequestBody(new NameValuePair[]{name, pass});
int status = client.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
//查看cookie 信息
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match(LOGON_STR, 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
GetMethod get = new GetMethod("/b.jsp");
client.executeMethod(get);
System.out.println(get.getResponseBodyAsString());
get.releaseConnection();
}
}