参考了网上的一些资料,实现表单提交功能,如果需要登录则自动进行登录(适用于form-auth的情况)。
package test;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* 测试登录并提交表单功能
* @author adun
*/
public class HttpTest {
static HttpClient CONN = new HttpClient();
static String DATA_ACTION = "http://localhost:8000/proc.jsp";
static String SIGNIN_ACTION = "http://localhost:8000/j_security_check";
public static void main(String[] args) throws Exception {
if(!postData()) {
System.out.println("尚未登录,尝试自动登录...");
postSignin();
postData();
}
}
/**
* 提交数据
* @return 是否提交成功
* @throws Exception
*/
public static boolean postData() throws Exception {
UTF8PostMethod procPost = new UTF8PostMethod(DATA_ACTION);
procPost.addParameter("name", "天津爱通科技有限公司");
System.out.println("尝试提交数据...");
CONN.executeMethod(procPost);
String body = procPost.getResponseBodyAsString();
boolean success = body.indexOf("j_security_check") < 0;
if(!success) {
System.out.println("数据提交成功!");
}
return success;
}
/**
* 登录过程
* @throws Exception
*/
public static void postSignin() throws Exception {
UTF8PostMethod signinPost = new UTF8PostMethod(SIGNIN_ACTION);
signinPost.addParameter("j_username", "admin");
signinPost.addParameter("j_password", "admin");
CONN.executeMethod(signinPost);
}
}
/**
* 重写PostMethod以解决UTF-8编码问题
* @author adun
*/
class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}