/**
* 用来演示登录表单的示例
* @author NECSTHZ.zhaojianming
* @Modification{#} TestRed.java Create on 2009/02/17 11:39:27
* @version 1.0
* @JDK version used: jdk1.6
* @Copyright (c) 2008 by NECSTHZ
*/
package http.test;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.*;
import org.apache.commons.httpclient.methods.*;
/**
* @Description:TestRed.java
* @author NECSTHZ.zhaojianming
*/
public class TestRed {
static final String LOGON_SITE = "172.28.140.113";
static final int LOGON_PORT = 8080;
/**
* @method main
* @param args
* @author zhaojianming
*/
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
// 模拟登录页面
String url = "http://172.28.140.113:8080/jsp-examples/security/protected/index.jsp";
PostMethod post = new PostMethod(url);
client.executeMethod(post);
// 查看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());
}
}
PostMethod postnew = new PostMethod(
"http://172.28.140.113:8080/jsp-examples/security/protected/j_security_check");
NameValuePair name = new NameValuePair("j_username", "tomcat");
NameValuePair pass = new NameValuePair("j_password", "tomcat");
postnew.setRequestBody(new NameValuePair[] { name, pass });
Header hCookie = post.getResponseHeader("set-Cookie");
String cookie = hCookie.getValue();
Header hHost = post.getRequestHeader("Host");
Header hUserAgent = post.getRequestHeader("User-Agent");
if (hCookie == null || hHost == null || hUserAgent == null) {
return;
}
postnew.setRequestHeader("Cookie", cookie);
postnew.setRequestHeader(hHost);
postnew.setRequestHeader(hUserAgent);
int statusCode;
try {
statusCode = client.executeMethod(postnew);
System.out.println("@@@@@@@@2@@" + postnew.getStatusCode());
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
Header locationHeader = postnew.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("location:" + location);
} else {
System.err.println("Location field value is null.");
return;
}
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
post.releaseConnection();
postnew.releaseConnection();
System.err.println("over");
}
}
}