java|HttpClient模拟登录总结(不能跳转及跳转后不能登录)

最近在写一个模拟登录的程序,从网上找了很多资料,都没能有一个完整的例子可成功跳转登录后的页面,现把我的代码拿来与大家分享一下,希望可以帮到一些人吧。
其原理是:通过HttpClient模拟请求的消息头信息,利用其的PostMethod方法,去请求访问网站的后台处理action,并返回登录后的Cookie,然后将cookie信息写入,再以GetMethod方法,携带cookie信息去请求网站,成功后进行跳转到登录页面。
代码如下:

【java|HttpClient模拟登录总结(不能跳转及跳转后不能登录)】HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
"utf-8"); // 设置字符集
String logUrl = "http://192.168.2.38:8812/emlog/admin/index.php?action=login"; // 注意:这里一定的地址,一定是点击提交时所提交到的后台处理的地址。
postMethod = new PostMethod(logUrl);
postMethod.setRequestHeader("Referer",
"http://192.168.2.38:8812/emlog/admin/");
postMethod.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
// 用户名及密码
NameValuePair[] logData = https://www.it610.com/article/{ new NameValuePair("user", "lzw"),
new NameValuePair("pw", "lzw123456") };

postMethod.setRequestBody(logData);
postMethod.releaseConnection();
int code = client.executeMethod(postMethod);
Cookie[] cookies = client.getState().getCookies(); // 获得Cookie信息

String location = null;
if (code == HttpStatus.SC_MOVED_PERMANENTLY// 判断postMethod执行后的返回值
|| code == HttpStatus.SC_MOVED_TEMPORARILY
|| code == HttpStatus.SC_SEE_OTHER
|| code == HttpStatus.SC_TEMPORARY_REDIRECT) {
location = postMethod.getResponseHeader("location").getValue().toString();
String newUrl = toRedirectURL(location, postMethod.getURI());
String urlx = null;
getMethod = new GetMethod(newUrl);
client.getState().addCookies(cookies); // 添加cookie信息 ,注:这一步不可少,不添加,则跳转但未登录
client.executeMethod(getMethod);
getMethod.releaseConnection();
urlx="rundll32 url.dll,FileProtocolHandler "+newUrl; // 调用函数打开一个新标签页
Runtime.getRuntime().exec("cmd.exe /c start "+ urlx);
System.out.println("Redirect:"
+ getMethod.getStatusLine().toString());

}

/**
* 相对路径处理因一些程序写的不规范,其访问路径为相对路径,所以加其判断
* @param location
* @param lastURI
* @return
* @throws Exception
*/
private String toRedirectURL(String location, URI lastURI) throws Exception {
if (location == null || location.trim().length() == 0) {
location = "/";
}
String tmp = location.toLowerCase();
if (!tmp.startsWith("http://") && !tmp.startsWith("https://")) {
if (lastURI == null) {
throw new IllegalArgumentException(
"lastUrl is null, can not find relative protocol and host name");
}
return new URI(lastURI, location, false).toString();
}
return location;
}


    推荐阅读