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的例子。