/**
   * Sets cookies according to uri and responseHeaders
   *
   * @param uri the specified uri
   * @param responseHeaders a list of request headers
   * @throws IOException if some error of I/O operation occurs
   */
  @Override
  public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    if (uri == null || responseHeaders == null) {
      throw new IllegalArgumentException();
    }

    // parse and construct cookies according to the map
    List<HttpCookie> cookies = parseCookie(responseHeaders);
    for (HttpCookie cookie : cookies) {

      // if the cookie doesn't have a domain, set one. The policy will do validation.
      if (cookie.getDomain() == null) {
        cookie.setDomain(uri.getHost());
      }

      // if the cookie doesn't have a path, set one. If it does, validate it.
      if (cookie.getPath() == null) {
        cookie.setPath(pathToCookiePath(uri.getPath()));
      } else if (!HttpCookie.pathMatches(cookie, uri)) {
        continue;
      }

      // if the cookie has the placeholder port list "", set the port. Otherwise validate it.
      if ("".equals(cookie.getPortlist())) {
        cookie.setPortlist(Integer.toString(uri.getEffectivePort()));
      } else if (cookie.getPortlist() != null && !HttpCookie.portMatches(cookie, uri)) {
        continue;
      }

      // if the cookie conforms to the policy, add it into the store
      if (policy.shouldAccept(uri, cookie)) {
        store.add(uri, cookie);
      }
    }
  }
 public void processRequestCookie(
     HttpURLConnection connection, HashMap<String, String> cookieHeaders) {
   connection.setInstanceFollowRedirects(false);
   // -----------------------------------------------------------------------------------------------------
   // 1、获取所有的Cookie集合
   // -----------------------------------------------------------------------------------------------------
   CookieStore cookieStore = CookieStoreHandler.getInstance();
   List<Cookie> cookies = cookieStore.getCookies();
   if (null == cookies || cookies.size() <= 0) {
     return;
   }
   // -----------------------------------------------------------------------------------------------------
   // 2、获取CookieOrigin
   // -----------------------------------------------------------------------------------------------------
   CookieOrigin cookieOrigin = getCookieOrigin(connection);
   // -----------------------------------------------------------------------------------------------------
   // 3、过滤符合条件数据,获取符合的Cookie集合
   // -----------------------------------------------------------------------------------------------------
   CookieSpec cookieSpec = obtainCookieSpec();
   final List<Cookie> matchedCookies = new ArrayList<Cookie>();
   final Date now = new Date();
   boolean expired = false;
   for (final Cookie cookie : cookies) {
     if (cookie.isExpired(now)) { // 过期了..,没有设置expire不过期
       VolleyLog.v("Cookie " + cookie + " expired");
       expired = true;
     } else {
       if (cookieSpec.match(cookie, cookieOrigin)) {
         VolleyLog.v("Cookie " + cookie + " match " + cookieOrigin);
         matchedCookies.add(cookie);
       }
     }
   }
   // 有过期的Cookie存在,则去掉所有过期的Cookie
   if (expired) {
     cookieStore.clearExpired(now);
   }
   // -----------------------------------------------------------------------------------------------------
   // 4、将符合条件的Cookie字符串,设置成请求头headers Map中
   // -----------------------------------------------------------------------------------------------------
   String cookie = cookieSpec.formatCookies(matchedCookies);
   if (null != cookie && cookie.length() > 0) {
     cookieHeaders.put("Cookie", cookie);
   }
 }
Ejemplo n.º 3
0
  public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders)
      throws IOException {
    // pre-condition check
    if (uri == null || requestHeaders == null) {
      throw new IllegalArgumentException("Argument is null");
    }

    Map<String, List<String>> cookieMap = new java.util.HashMap<String, List<String>>();
    // if there's no default CookieStore, no way for us to get any cookie
    if (cookieJar == null) return Collections.unmodifiableMap(cookieMap);

    boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
    List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>();
    String path = uri.getPath();
    if (path == null || path.isEmpty()) {
      path = "/";
    }
    for (HttpCookie cookie : cookieJar.get(uri)) {
      // apply path-matches rule (RFC 2965 sec. 3.3.4)
      // and check for the possible "secure" tag (i.e. don't send
      // 'secure' cookies over unsecure links)
      if (pathMatches(path, cookie.getPath()) && (secureLink || !cookie.getSecure())) {
        // Enforce httponly attribute
        if (cookie.isHttpOnly()) {
          String s = uri.getScheme();
          if (!"http".equalsIgnoreCase(s) && !"https".equalsIgnoreCase(s)) {
            continue;
          }
        }
        // Let's check the authorize port list if it exists
        String ports = cookie.getPortlist();
        if (ports != null && !ports.isEmpty()) {
          int port = uri.getPort();
          if (port == -1) {
            port = "https".equals(uri.getScheme()) ? 443 : 80;
          }
          if (isInPortList(ports, port)) {
            cookies.add(cookie);
          }
        } else {
          cookies.add(cookie);
        }
      }
    }

    // apply sort rule (RFC 2965 sec. 3.3.4)
    List<String> cookieHeader = sortByPath(cookies);

    cookieMap.put("Cookie", cookieHeader);
    return Collections.unmodifiableMap(cookieMap);
  }
  /**
   * Searches and gets all cookies in the cache by the specified uri in the request header.
   *
   * @param uri the specified uri to search for
   * @param requestHeaders a list of request headers
   * @return a map that record all such cookies, the map is unchangeable
   * @throws IOException if some error of I/O operation occurs
   */
  @Override
  public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders)
      throws IOException {
    if (uri == null || requestHeaders == null) {
      throw new IllegalArgumentException();
    }

    List<HttpCookie> result = new ArrayList<HttpCookie>();
    for (HttpCookie cookie : store.get(uri)) {
      if (HttpCookie.pathMatches(cookie, uri)
          && HttpCookie.secureMatches(cookie, uri)
          && HttpCookie.portMatches(cookie, uri)) {
        result.add(cookie);
      }
    }

    return cookiesToHeaders(result);
  }
Ejemplo n.º 5
0
 /**
  * TODO Documentation
  *
  * @param url the rest service URL to request
  * @return the resulting {@link ClientResponse}. If the request fails (HTTP response code NOT 200)
  *     <code>null</code> will be returned.
  */
 private ClientResponse request(final String url) {
   // Set the cookies
   if (loginCookies == null) {
     // TODO throw a real exception here
     throw new RuntimeException("Please login first");
   }
   // build the request
   final DefaultClientConfig cc = new DefaultClientConfig();
   final Client client = Client.create(cc);
   final WebResource resource = client.resource(url);
   final Builder builder = resource.getRequestBuilder();
   builder.accept(MediaType.APPLICATION_XML);
   for (Cookie cookie : loginCookies.getCookies()) {
     builder.cookie(cookie);
   }
   final ClientResponse response = builder.get(ClientResponse.class);
   if (response.getStatus() != 200) {
     LOG.warning("Request failed! HTTP response code: " + response.getStatus());
   }
   return response;
 }
Ejemplo n.º 6
0
  public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
    // pre-condition check
    if (uri == null || responseHeaders == null) {
      throw new IllegalArgumentException("Argument is null");
    }

    // if there's no default CookieStore, no need to remember any cookie
    if (cookieJar == null) return;

    PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
    for (String headerKey : responseHeaders.keySet()) {
      // RFC 2965 3.2.2, key must be 'Set-Cookie2'
      // we also accept 'Set-Cookie' here for backward compatibility
      if (headerKey == null
          || !(headerKey.equalsIgnoreCase("Set-Cookie2")
              || headerKey.equalsIgnoreCase("Set-Cookie"))) {
        continue;
      }

      for (String headerValue : responseHeaders.get(headerKey)) {
        try {
          List<HttpCookie> cookies;
          try {
            cookies = HttpCookie.parse(headerValue);
          } catch (IllegalArgumentException e) {
            // Bogus header, make an empty list and log the error
            cookies = java.util.Collections.EMPTY_LIST;
            if (logger.isLoggable(PlatformLogger.SEVERE)) {
              logger.severe("Invalid cookie for " + uri + ": " + headerValue);
            }
          }
          for (HttpCookie cookie : cookies) {
            if (cookie.getPath() == null) {
              // If no path is specified, then by default
              // the path is the directory of the page/doc
              String path = uri.getPath();
              if (!path.endsWith("/")) {
                int i = path.lastIndexOf("/");
                if (i > 0) {
                  path = path.substring(0, i + 1);
                } else {
                  path = "/";
                }
              }
              cookie.setPath(path);
            }

            // As per RFC 2965, section 3.3.1:
            // Domain  Defaults to the effective request-host.  (Note that because
            // there is no dot at the beginning of effective request-host,
            // the default Domain can only domain-match itself.)
            if (cookie.getDomain() == null) {
              cookie.setDomain(uri.getHost());
            }
            String ports = cookie.getPortlist();
            if (ports != null) {
              int port = uri.getPort();
              if (port == -1) {
                port = "https".equals(uri.getScheme()) ? 443 : 80;
              }
              if (ports.isEmpty()) {
                // Empty port list means this should be restricted
                // to the incoming URI port
                cookie.setPortlist("" + port);
                if (shouldAcceptInternal(uri, cookie)) {
                  cookieJar.add(uri, cookie);
                }
              } else {
                // Only store cookies with a port list
                // IF the URI port is in that list, as per
                // RFC 2965 section 3.3.2
                if (isInPortList(ports, port) && shouldAcceptInternal(uri, cookie)) {
                  cookieJar.add(uri, cookie);
                }
              }
            } else {
              if (shouldAcceptInternal(uri, cookie)) {
                cookieJar.add(uri, cookie);
              }
            }
          }
        } catch (IllegalArgumentException e) {
          // invalid set-cookie header string
          // no-op
        }
      }
    }
  }