模拟站点的自动登录发帖回复
2009-09-21 00:00:00 来源:WEB开发网Java代码
/**
* 站点登录
*/
public class SiteLogin extends AbstractMethodAdapter
{
private HttpMethodBase method;
private boolean ispost=true;
protected BrowserContext context; //当前的浏览器进程上下文
public BrowserContext getContext() {
return context;
}
/** *//**
* 构造函数
* @param context
* @param url
* @param ispost 设置是否POST方式提交,默认为POST
*/
public SiteLogin(BrowserContext context,String url,boolean ispost) {
super();
this.context = context;
this.ispost=ispost;
method = this.ispost?new PostMethod(url):new GetMethod(url);
}
public SiteLogin(BrowserContext context,String url) {
this(context,url,true);
}
public String login(Siteusers user)
{
int statusCode=0;
if(this.ispost && this.hasRequestParameters()){
((PostMethod)method).setRequestBody(this.getRequestParams());
}
if(this.hasExtraRequestHeaders()){
this.addExtraRequestHeaders(method,this.getExtraRequestHeaders());
}
context.setCommonMethodRequestHeaders(method);
try
{
if(context.getCookies()!=null){
//printCookies();
context.getClient().getState().addCookies(context.getCookies());
method.addRequestHeader("Cookie", context.getCookies().toString());
}
statusCode = context.getClient().executeMethod(method);
context.setCookies(context.getClient().getState().getCookies());
String responseString = method.getResponseBodyAsString();
//System.out.println(responseString);
method.releaseConnection();
if(statusCode==HttpStatus.SC_OK){
System.out.println("登录成功");
return responseString;
}
else if(statusCode==302 ||statusCode==301){
System.out.println("登录成功,页面重定向");
String url=method.getResponseHeader("Location").getValue();
return context.redirectToURL(url);
}
else{
System.out.println("登录失败,状态码:"+statusCode);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(method!=null)
method.releaseConnection();
}
return null;
}
}
更多精彩
赞助商链接