开发学院软件开发Java 模拟站点的自动登录发帖回复 阅读

模拟站点的自动登录发帖回复

 2009-09-21 00:00:00 来源:WEB开发网   
核心提示: Java代码 /***站点登录*/publicclassSiteLoginextendsAbstractMethodAdapter{privateHttpMethodBasemethod;privatebooleanispost=true;protectedBrowserContextconte

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;
  }
}

上一页  1 2 3 4 5  下一页

Tags:模拟 站点 自动

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接