直接上代码了,代码里面有详细的注释
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class test {
public static void main(String[] args) {
try {
// 先访问首页,得到cookie
// cookie信息自动保存在HttpClient中
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://1.lexury2016.sinaapp.com/login");
httpClient.executeMethod(postMethod);
// 携带cookie访问登录网面
postMethod = new PostMethod("http://1.lexury2016.sinaapp.com/login");
// 设置登录的账号与密码
NameValuePair[] nameValuePairs = { new NameValuePair("stucid", "2013150091"),
new NameValuePair("stupassword", "ab1234") };
postMethod.setRequestBody(nameValuePairs);
// 设置请求编码为UTF-8
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
// httpclient访问登录网页
httpClient.executeMethod(postMethod);
// 得到响应文本
byte[] bytes = postMethod.getResponseBody();
String html = new String(bytes);
System.out.println(postMethod.getStatusCode());
// 输出为302,也就是说网页发生了重定向
// 得到重定向后的网页
Header redirect = postMethod.getResponseHeader("location");
String url = redirect.getValue();
// 使用get请求,访问登陆后的页面
GetMethod getMethod = new GetMethod(url);
httpClient.executeMethod(getMethod);
// 得到返回文本
bytes = getMethod.getResponseBody();
html = new String(bytes);
System.out.println(html);
} catch (Exception e) {
e.printStackTrace();
}
}
}