/**
     * Validate cookie path attribute. The value for the Path attribute must be a prefix of the
     * request-URI (case-sensitive matching).
     */
    public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
      if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
      }
      if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
      }
      String path = origin.getPath();
      if (path == null) {
        throw new IllegalArgumentException("Path of origin host may not be null.");
      }
      if (cookie.getPath() == null) {
        throw new MalformedCookieException("Invalid cookie state: " + "path attribute is null.");
      }
      if (path.trim().equals("")) {
        path = PATH_DELIM;
      }

      if (!pathMatch(path, cookie.getPath())) {
        throw new MalformedCookieException(
            "Illegal path attribute \""
                + cookie.getPath()
                + "\". Path of origin: \""
                + path
                + "\"");
      }
    }
  private void doLogin(final PremiumAccount pa) throws Exception {
    HttpMethod method =
        getMethodBuilder()
            .setAction("https://www.4shared.com/web/login")
            .setAjax()
            .setParameter("returnTo", fileURL)
            .setParameter("login", pa.getUsername())
            .setParameter("password", pa.getPassword())
            .toPostMethod();
    if (!makeRedirectedRequest(method)) {
      throw new ServiceConnectionProblemException("Error posting login info");
    }
    if (getContentAsString().contains("Invalid e-mail address or password")) {
      throw new BadLoginException("Invalid 4Shared account login information");
    }

    // language is based on account pref,
    // setting language cookie doesn't work
    Cookie langCookie = getCookieByName("4langcookie");
    if ((langCookie == null) || !langCookie.getValue().equalsIgnoreCase("en")) {
      method =
          getMethodBuilder()
              .setAction(
                  "http://www.4shared.com/web/user/language") // set account's language preference
              .setParameter("code", "en")
              .toPostMethod();
      if (!makeRedirectedRequest(method)) {
        throw new ServiceConnectionProblemException();
      }
      if (!getContentAsString().contains("\"status\":\"ok\"")) {
        throw new PluginImplementationException("Setting language to EN failed");
      }
    }
  }
  private Cookie getSessionCookie(Cookie[] cookies) {
    for (Cookie cookie : cookies) {
      if ("JSESSIONID".equals(cookie.getName())) {
        return cookie;
      }
    }

    return null;
  }
示例#4
0
 /**
  * 构建阶段时输出cookie值
  *
  * @param client
  */
 private static void printCookie(HttpClient client) {
   Cookie[] cookies = client.getState().getCookies();
   System.out.println("目前有" + cookies.length + "条cookie");
   int index = 0;
   for (Cookie cookie : cookies) {
     System.out.println(
         "cookie[" + index + "]:{" + cookie.getName() + "," + cookie.getValue() + "}");
     index++;
   }
 }
  public String getCookiesString() {
    Cookie[] cookies = getState().getCookies();
    String cookiesString = "";
    for (Cookie cookie : cookies) {
      cookiesString = cookiesString + cookie.toString() + ";";

      // logCookie(cookie);
    }

    return cookiesString;
  }
 private void getPreload() throws Exception {
   final HttpMethod method = getGetMethod("http://grooveshark.com/preload.php");
   if (!makeRedirectedRequest(method)) {
     throw new ServiceConnectionProblemException();
   }
   final Cookie cookie = getCookieByName("PHPSESSID");
   if (cookie == null) {
     throw new PluginImplementationException("Session cookie not found");
   }
   sessionId = cookie.getValue();
   uuid = UUID.randomUUID().toString().toUpperCase(Locale.ROOT);
 }
 /** Parse cookie path attribute. */
 public void parse(final Cookie cookie, final String path) throws MalformedCookieException {
   if (cookie == null) {
     throw new IllegalArgumentException("Cookie may not be null");
   }
   if (path == null) {
     throw new MalformedCookieException("Missing value for path attribute");
   }
   if (path.trim().equals("")) {
     throw new MalformedCookieException("Blank value for path attribute");
   }
   cookie.setPath(path);
   cookie.setPathAttributeSpecified(true);
 }
  protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) {

    org.apache.commons.httpclient.Cookie commonsCookie =
        new org.apache.commons.httpclient.Cookie(
            cookie.getDomain(),
            cookie.getName(),
            cookie.getValue(),
            cookie.getPath(),
            cookie.getMaxAge(),
            cookie.getSecure());

    commonsCookie.setVersion(cookie.getVersion());

    return commonsCookie;
  }
 private void logCookie(Cookie cookie) {
   Log_OC.d(TAG, "Cookie name: " + cookie.getName());
   Log_OC.d(TAG, "       value: " + cookie.getValue());
   Log_OC.d(TAG, "       domain: " + cookie.getDomain());
   Log_OC.d(TAG, "       path: " + cookie.getPath());
   Log_OC.d(TAG, "       version: " + cookie.getVersion());
   Log_OC.d(
       TAG,
       "       expiryDate: "
           + (cookie.getExpiryDate() != null ? cookie.getExpiryDate().toString() : "--"));
   Log_OC.d(TAG, "       comment: " + cookie.getComment());
   Log_OC.d(TAG, "       secure: " + cookie.getSecure());
 }
 private void validateCookie(Cookie cookie) {
   if ("cookie1".equals(cookie.getName())) {
     assertEquals("value1", cookie.getValue());
     assertEquals("/", cookie.getPath());
     assertEquals("localhost", cookie.getDomain());
     validateDate(cookie.getExpiryDate());
     assertTrue(cookie.getSecure());
   } else {
     assertEquals("cookie2", cookie.getName());
     assertEquals("value2", cookie.getValue());
     assertFalse(cookie.getSecure());
   }
 }
  protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) {

    Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue());

    String domain = commonsCookie.getDomain();

    if (Validator.isNotNull(domain)) {
      cookie.setDomain(domain);
    }

    Date expiryDate = commonsCookie.getExpiryDate();

    if (expiryDate != null) {
      int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis());

      maxAge = maxAge / 1000;

      if (maxAge > -1) {
        cookie.setMaxAge(maxAge);
      }
    }

    String path = commonsCookie.getPath();

    if (Validator.isNotNull(path)) {
      cookie.setPath(path);
    }

    cookie.setSecure(commonsCookie.getSecure());
    cookie.setVersion(commonsCookie.getVersion());

    return cookie;
  }
 public boolean match(final Cookie cookie, final CookieOrigin origin) {
   if (cookie == null) {
     throw new IllegalArgumentException("Cookie may not be null");
   }
   if (origin == null) {
     throw new IllegalArgumentException("Cookie origin may not be null");
   }
   return cookie.getSecure() == origin.isSecure();
 }
示例#13
0
  private void checkHeaders(HTTPMethod method) {
    if (debugHeaders) {
      System.out.println("\nOpenConnection Headers for " + method.getPath());
      System.out.println("Status Line: " + method.getStatusLine());
    }

    Header[] responseHeaders = method.getResponseHeaders();
    for (int i1 = 0; i1 < responseHeaders.length; i1++) {
      Header responseHeader = responseHeaders[i1];
      if (debugHeaders) System.out.print("  " + responseHeader);
      String key = responseHeader.getName();
      String value = responseHeader.getValue();

      if (key.equals("Last-Modified")) {
        lastModified = value;
        if (debugHeaders) System.out.println(" **found lastModified = " + lastModified);

      } else if (key.equals("X-Last-Extended")) {
        lastExtended = value;
        if (debugHeaders) System.out.println(" **found lastExtended = " + lastExtended);

      } else if (key.equals("X-Last-Modified-Invalid")) {
        lastModifiedInvalid = value;
        if (debugHeaders)
          System.out.println(" **found lastModifiedInvalid = " + lastModifiedInvalid);
      }
    }

    if (debugHeaders) System.out.println("OpenConnection Headers for " + method.getPath());

    Cookie[] cookies = _session.getCookies();

    if (cookies.length > 0) {
      if (debugHeaders) System.out.println("Cookies= ");

      for (int i = 0; i < cookies.length; i++) {
        Cookie cooky = cookies[i];
        if (debugHeaders) System.out.println("  " + cooky);
        if (cooky.getName().equalsIgnoreCase("jsessionid")) hasSession = true;
      }
    }
  }
示例#14
0
  /**
   * 获取主页列表
   *
   * @param client
   * @throws IOException
   * @throws HttpException
   */
  public static void fetchHomePage(HttpClient client) throws Exception {
    // 获得登陆后的 Cookie
    Cookie[] cookies = client.getState().getCookies();
    String tmpcookies = "";
    for (Cookie c : cookies) {
      tmpcookies += c.toString() + ";";
    }
    // 进行登陆后的操作
    GetMethod getMethod = new GetMethod("http://www.catarc.org.cn/standard/SearchStandard.aspx");
    // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
    getMethod.setRequestHeader("cookie", tmpcookies);
    client.executeMethod(getMethod);
    String text = getMethod.getResponseBodyAsString();

    setViewState(text);

    setEventValidation(text);

    setStandardIdsToMap(1, text);
  }
    /**
     * Match cookie path attribute. The value for the Path attribute must be a prefix of the
     * request-URI (case-sensitive matching).
     */
    public boolean match(final Cookie cookie, final CookieOrigin origin) {
      if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
      }
      if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
      }
      String path = origin.getPath();
      if (cookie.getPath() == null) {
        LOG.warn("Invalid cookie state: path attribute is null.");
        return false;
      }
      if (path.trim().equals("")) {
        path = PATH_DELIM;
      }

      if (!pathMatch(path, cookie.getPath())) {
        return false;
      }
      return true;
    }
示例#16
0
  public static void login() throws Exception {

    // Dem Client den Benutzernamen und das Kennwort übergeben
    HttpClient client = new HttpClient();
    client.getParams().setParameter("vb_login_username", "Programmierklasse");
    client.getParams().setParameter("vb_login_password", "987654");

    // Text von der Forumseite abholen
    GetMethod method =
        new GetMethod(
            "http://forum.operationgamma41.de/showthread.php?1228-Erfassung-der-Moderationszeiten-!");
    try {
      client.executeMethod(method);
      Cookie[] cookies = client.getState().getCookies();
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        System.err.println(
            "Cookie: "
                + cookie.getName()
                + ", Value: "
                + cookie.getValue()
                + ", IsPersistent?: "
                + cookie.isPersistent()
                + ", Expiry Date: "
                + cookie.getExpiryDate()
                + ", Comment: "
                + cookie.getComment());
      }
      client.executeMethod(method);
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      method.releaseConnection();
    }
  }
  /**
   * Create a RFC 2965 compliant <tt>"Cookie"</tt> header value containing all {@link
   * org.apache.commons.httpclient.Cookie}s suitable for sending in a <tt>"Cookie"</tt> header
   *
   * @param cookies an array of {@link org.apache.commons.httpclient.Cookie}s to be formatted
   * @return a string suitable for sending in a Cookie header.
   */
  public String formatCookies(final Cookie[] cookies) {
    LOG.trace("enter RFC2965Spec.formatCookieHeader(Cookie[])");

    if (cookies == null) {
      throw new IllegalArgumentException("Cookies may not be null");
    }
    // check if cookies array contains a set-cookie (old style) cookie
    boolean hasOldStyleCookie = false;
    int version = -1;
    for (int i = 0; i < cookies.length; i++) {
      Cookie cookie = cookies[i];
      if (!(cookie instanceof Cookie2)) {
        hasOldStyleCookie = true;
        break;
      }
      if (cookie.getVersion() > version) {
        version = cookie.getVersion();
      }
    }
    if (version < 0) {
      version = 0;
    }
    if (hasOldStyleCookie || version < 1) {
      // delegate old-style cookie formatting to rfc2109Spec
      return this.rfc2109.formatCookies(cookies);
    }
    // Arrange cookies by path
    Arrays.sort(cookies, PATH_COMPOARATOR);

    final StringBuffer buffer = new StringBuffer();
    // format cookie version
    this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
    for (int i = 0; i < cookies.length; i++) {
      buffer.append("; ");
      Cookie2 cookie = (Cookie2) cookies[i];
      // format cookie attributes
      doFormatCookie2(cookie, buffer);
    }
    return buffer.toString();
  }
 /** Parse cookie domain attribute. */
 public void parse(final Cookie cookie, String domain) throws MalformedCookieException {
   if (cookie == null) {
     throw new IllegalArgumentException("Cookie may not be null");
   }
   if (domain == null) {
     throw new MalformedCookieException("Missing value for domain attribute");
   }
   if (domain.trim().equals("")) {
     throw new MalformedCookieException("Blank value for domain attribute");
   }
   domain = domain.toLowerCase();
   if (!domain.startsWith(".")) {
     // Per RFC 2965 section 3.2.2
     // "... If an explicitly specified value does not start with
     // a dot, the user agent supplies a leading dot ..."
     // That effectively implies that the domain attribute
     // MAY NOT be an IP address of a host name
     domain = "." + domain;
   }
   cookie.setDomain(domain);
   cookie.setDomainAttributeSpecified(true);
 }
  /**
   * Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation
   *
   * @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received
   * @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received
   * @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received
   * @param secure <tt>true</tt> when the {@link org.apache.commons.httpclient.Cookie} was received
   *     using a secure connection
   * @param cookie The cookie to validate
   * @throws MalformedCookieException if an exception occurs during validation
   */
  public void validate(
      final String host, int port, final String path, boolean secure, final Cookie cookie)
      throws MalformedCookieException {

    LOG.trace("enter RFC2965Spec.validate(String, int, String, " + "boolean, Cookie)");

    if (cookie instanceof Cookie2) {
      if (cookie.getName().indexOf(' ') != -1) {
        throw new MalformedCookieException("Cookie name may not contain blanks");
      }
      if (cookie.getName().startsWith("$")) {
        throw new MalformedCookieException("Cookie name may not start with $");
      }
      CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure);
      for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
        CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
        handler.validate(cookie, origin);
      }
    } else {
      // old-style cookies are validated according to the old rules
      this.rfc2109.validate(host, port, path, secure, cookie);
    }
  }
  /**
   * Return <tt>true</tt> if the cookie should be submitted with a request with given attributes,
   * <tt>false</tt> otherwise.
   *
   * @param host the host to which the request is being submitted
   * @param port the port to which the request is being submitted (ignored)
   * @param path the path to which the request is being submitted
   * @param secure <tt>true</tt> if the request is using a secure connection
   * @return true if the cookie matches the criterium
   */
  public boolean match(String host, int port, String path, boolean secure, final Cookie cookie) {

    LOG.trace("enter RFC2965.match(" + "String, int, String, boolean, Cookie");
    if (cookie == null) {
      throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
      // check if cookie has expired
      if (cookie.isPersistent() && cookie.isExpired()) {
        return false;
      }
      CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure);
      for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
        CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
        if (!handler.match(cookie, origin)) {
          return false;
        }
      }
      return true;
    } else {
      // old-style cookies are matched according to the old rules
      return this.rfc2109.match(host, port, path, secure, cookie);
    }
  }
 /**
  * Create a new cookie with domain, name, value, path and expires.
  *
  * @param domain the domain
  * @param name the name
  * @param value the value
  * @param path the path
  * @param expires the expires
  * @return a new cookie
  */
 protected Cookie createCookie(
     String domain, String name, String value, String path, long expires) {
   Cookie cookie = new Cookie();
   cookie.setDomain(domain);
   cookie.setName(name);
   cookie.setValue(value);
   cookie.setPath(path);
   cookie.setExpiryDate(new Date(System.currentTimeMillis() + expires));
   return cookie;
 }
 /** Parse cookie max-age attribute. */
 public void parse(final Cookie cookie, final String value) throws MalformedCookieException {
   if (cookie == null) {
     throw new IllegalArgumentException("Cookie may not be null");
   }
   if (value == null) {
     throw new MalformedCookieException("Missing value for max-age attribute");
   }
   int age = -1;
   try {
     age = Integer.parseInt(value);
   } catch (NumberFormatException e) {
     age = -1;
   }
   if (age < 0) {
     throw new MalformedCookieException("Invalid max-age attribute.");
   }
   cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
 }
示例#23
0
 private String getHttpCookie() {
   StringBuilder strHeader = new StringBuilder();
   Cookie[] cookies = httpClient.getState().getCookies();
   for (Cookie cookie : cookies) {
     String domain = cookie.getDomain();
     String path = cookie.getPath();
     String name = cookie.getName();
     String value = cookie.getValue();
     Date expired = cookie.getExpiryDate();
     boolean isSecure = cookie.getSecure();
     strHeader.append("domain=" + domain + ";");
     strHeader.append("path=" + path + ";");
     strHeader.append(name + "=" + value + ";");
     if (expired != null) {
       strHeader.append("expired=" + expired.toGMTString() + ";");
     }
     strHeader.append("isSecure=" + isSecure + "/n");
   }
   return strHeader.toString();
 }
    /** Match cookie domain attribute. */
    public boolean match(final Cookie cookie, final CookieOrigin origin) {
      if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
      }
      if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
      }
      String host = origin.getHost().toLowerCase();
      String cookieDomain = cookie.getDomain();

      // The effective host name MUST domain-match the Domain
      // attribute of the cookie.
      if (!domainMatch(host, cookieDomain)) {
        return false;
      }
      // effective host name minus domain must not contain any dots
      String effectiveHostWithoutDomain = host.substring(0, host.length() - cookieDomain.length());
      if (effectiveHostWithoutDomain.indexOf('.') != -1) {
        return false;
      }
      return true;
    }
 public void parse(final Cookie cookie, final String comment) throws MalformedCookieException {
   cookie.setComment(comment);
 }
 public void parse(final Cookie cookie, final String secure) throws MalformedCookieException {
   cookie.setSecure(true);
 }
    /** Validate cookie domain attribute. */
    public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
      if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
      }
      if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
      }
      String host = origin.getHost().toLowerCase();
      if (cookie.getDomain() == null) {
        throw new MalformedCookieException("Invalid cookie state: " + "domain not specified");
      }
      String cookieDomain = cookie.getDomain().toLowerCase();

      if (cookie.isDomainAttributeSpecified()) {
        // Domain attribute must start with a dot
        if (!cookieDomain.startsWith(".")) {
          throw new MalformedCookieException(
              "Domain attribute \""
                  + cookie.getDomain()
                  + "\" violates RFC 2109: domain must start with a dot");
        }

        // Domain attribute must contain atleast one embedded dot,
        // or the value must be equal to .local.
        int dotIndex = cookieDomain.indexOf('.', 1);
        if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
            && (!cookieDomain.equals(".local"))) {
          throw new MalformedCookieException(
              "Domain attribute \""
                  + cookie.getDomain()
                  + "\" violates RFC 2965: the value contains no embedded dots "
                  + "and the value is not .local");
        }

        // The effective host name must domain-match domain attribute.
        if (!domainMatch(host, cookieDomain)) {
          throw new MalformedCookieException(
              "Domain attribute \""
                  + cookie.getDomain()
                  + "\" violates RFC 2965: effective host name does not "
                  + "domain-match domain attribute.");
        }

        // effective host name minus domain must not contain any dots
        String effectiveHostWithoutDomain =
            host.substring(0, host.length() - cookieDomain.length());
        if (effectiveHostWithoutDomain.indexOf('.') != -1) {
          throw new MalformedCookieException(
              "Domain attribute \""
                  + cookie.getDomain()
                  + "\" violates RFC 2965: "
                  + "effective host minus domain may not contain any dots");
        }
      } else {
        // Domain was not specified in header. In this case, domain must
        // string match request host (case-insensitive).
        if (!cookie.getDomain().equals(host)) {
          throw new MalformedCookieException(
              "Illegal domain attribute: \""
                  + cookie.getDomain()
                  + "\"."
                  + "Domain of origin: \""
                  + host
                  + "\"");
        }
      }
    }