public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) { if (cookieStore != null) { this.cookies = cookieStore.getCookies().toArray(new Cookie[0]); } if (httpResponse != null) { this.headers = httpResponse.getAllHeaders(); this.statuCode = httpResponse.getStatusLine().getStatusCode(); if(d)System.out.println(this.statuCode); try { this.response = EntityUtils.toByteArray(httpResponse .getEntity()); } catch (IOException e) { e.printStackTrace(); } } }
/** * Adds an {@link Cookie HTTP cookie}, replacing any existing equivalent cookies. * If the given cookie has already expired it will not be added, but existing * values will still be removed. * * @param cookie the {@link Cookie cookie} to be added * @see #addCookies(Cookie[]) */ @Override public synchronized void addCookie(final Cookie cookie) { if (cookie != null) { // first remove any old cookie that is equivalent cookies.remove(cookie); Date now = new Date(); if (!cookie.isExpired(now)) { Date targetExpiryDate = new Date(System.currentTimeMillis() + maxExpiresMillis); if (!cookie.isExpired(targetExpiryDate)) { try { if (cookie instanceof BasicClientCookie) { ((BasicClientCookie) cookie).setExpiryDate(targetExpiryDate); } else if (cookie instanceof BasicClientCookie2) { ((BasicClientCookie2) cookie).setExpiryDate(targetExpiryDate); } } catch (Exception e) { } } cookies.add(cookie); } } }
/** * Remove a Cookie by name and path * * @param name cookie name * @param path cookie path */ @PublicAtsApi public void removeCookie( String name, String path ) { BasicCookieStore cookieStore = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE); if (cookieStore != null) { List<Cookie> cookies = cookieStore.getCookies(); cookieStore.clear(); for (Cookie cookie : cookies) { if (!cookie.getName().equals(name) || !cookie.getPath().equals(path)) { cookieStore.addCookie(cookie); } } } }
@Override protected void buildCookie(com.intuit.karate.http.Cookie c) { BasicClientCookie cookie = new BasicClientCookie(c.getName(), c.getValue()); for (Entry<String, String> entry : c.entrySet()) { switch (entry.getKey()) { case DOMAIN: cookie.setDomain(entry.getValue()); break; case PATH: cookie.setPath(entry.getValue()); break; } } if (cookie.getDomain() == null) { cookie.setDomain(uriBuilder.getHost()); } cookieStore.addCookie(cookie); }
public PersistentCookieStore(Context context) { int i = 0; this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null); if (storedCookieNames != null) { String[] cookieNames = TextUtils.split(storedCookieNames, ","); int length = cookieNames.length; while (i < length) { String name = cookieNames[i]; String encodedCookie = this.cookiePrefs.getString(new StringBuilder(COOKIE_NAME_PREFIX).append(name).toString(), null); if (encodedCookie != null) { Cookie decodedCookie = decodeCookie(encodedCookie); if (decodedCookie != null) { this.cookies.put(name, decodedCookie); } } i++; } clearExpired(new Date()); } }
public boolean clearExpired(Date date) { boolean clearedAny = false; Editor prefsWriter = this.cookiePrefs.edit(); for (Entry<String, Cookie> entry : this.cookies.entrySet()) { String name = (String) entry.getKey(); if (((Cookie) entry.getValue()).isExpired(date)) { this.cookies.remove(name); prefsWriter.remove(new StringBuilder(COOKIE_NAME_PREFIX).append(name).toString()); clearedAny = true; } } if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet())); } prefsWriter.commit(); return clearedAny; }
@Override public boolean clearExpired(Date date) { boolean clearedAny = false; SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) { String name = entry.getKey(); Cookie cookie = entry.getValue(); if (cookie.isExpired(date)) { // Clear cookies from local store cookies.remove(name); // Clear cookies from persistent store prefsWriter.remove(COOKIE_NAME_PREFIX + name); // We've cleared at least one clearedAny = true; } } // Update names in persistent store if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); } prefsWriter.apply(); return clearedAny; }
public boolean clearExpired(Date date) { boolean clearedAny = false; Editor prefsWriter = this.cookiePrefs.edit(); for (Entry<String, Cookie> entry : this.cookies.entrySet()) { String name = (String) entry.getKey(); if (((Cookie) entry.getValue()).isExpired(date)) { this.cookies.remove(name); prefsWriter.remove(COOKIE_NAME_PREFIX + name); clearedAny = true; } } if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet())); } prefsWriter.commit(); return clearedAny; }
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { final HttpClientContext clientContext = HttpClientContext.adapt(httpContext); List<Cookie> cookies = clientContext.getCookieStore().getCookies(); boolean set = (null != StickyCookieHolder.getTestStickySessionCookie()); boolean found = false; ListIterator<Cookie> it = cookies.listIterator(); while (it.hasNext()) { Cookie cookie = it.next(); if (cookie.getName().equals(StickyCookieHolder.COOKIE_NAME)) { found = true; if (set) { // set the cookie with the value saved for each thread using the rule it.set(StickyCookieHolder.getTestStickySessionCookie()); } else { // if the cookie is not set in TestStickySessionRule, remove it from here it.remove(); } } } // if the cookie needs to be set from TestStickySessionRule but did not exist in the client cookie list, add it here. if (!found && set) { cookies.add(StickyCookieHolder.getTestStickySessionCookie()); } BasicCookieStore cs = new BasicCookieStore(); cs.addCookies(cookies.toArray(new Cookie[cookies.size()])); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cs); }
public void saveCookie(Cookie cookie) { L.d("saveCookie:" + cookie); if (cookie == null) { return; } db.delete(TABLE_NAME, Column.NAME + " = ? ", new String[] { cookie.getName() }); ContentValues values = new ContentValues(); values.put(Column.VALUE, cookie.getValue()); values.put(Column.NAME, cookie.getName()); values.put(Column.COMMENT, cookie.getComment()); values.put(Column.DOMAIN, cookie.getDomain()); if (cookie.getExpiryDate() != null) { values.put(Column.EXPIRY_DATE, cookie.getExpiryDate().getTime()); } values.put(Column.PATH, cookie.getPath()); values.put(Column.SECURE, cookie.isSecure() ? 1 : 0); values.put(Column.VERSION, cookie.getVersion()); db.insert(TABLE_NAME, null, values); }
public PersistentCookieStore(Context context) { int i = 0; this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); this.cookies = new ConcurrentHashMap(); String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null); if (storedCookieNames != null) { String[] cookieNames = TextUtils.split(storedCookieNames, ","); int length = cookieNames.length; while (i < length) { String name = cookieNames[i]; String encodedCookie = this.cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null); if (encodedCookie != null) { Cookie decodedCookie = decodeCookie(encodedCookie); if (decodedCookie != null) { this.cookies.put(name, decodedCookie); } } i++; } clearExpired(new Date()); } }
public void saveCookies(List<Cookie> cookies){ String strCookie = ""; Date sessionTime = null; if (cookies != null && !cookies.isEmpty()) { for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); if (cookie.getName().equalsIgnoreCase("JSESSIONID")){ strCookie += cookie.getName() + "=" + cookie.getValue() + ";domain=" +cookie.getDomain(); sessionTime = cookies.get(i).getExpiryDate(); } } } editor.putString("cookies", strCookie); editor.commit(); editor.putString("cookiesExpiryDate", (sessionTime == null)?null:TimeUtil.getDTFormat().format(sessionTime)); editor.commit(); }
@Override public void afterPropertiesSet() throws Exception { cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider> create().register("easy", new CookieSpecProvider() { public CookieSpec create(HttpContext context) { return new DefaultCookieSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { } }; } }).build(); requestConfig = RequestConfig.custom().setCookieSpec("easy") .setConnectionRequestTimeout(propertyConfigurer.getIntValue("connection.request.timeout")) .setSocketTimeout(propertyConfigurer.getIntValue("socket_timeout")) .setConnectTimeout(propertyConfigurer.getIntValue("connection_timeout")).build(); }
@Override public void addCookie(Cookie cookie) { if (omitNonPersistentCookies && !cookie.isPersistent()) return; String name = cookie.getName() + cookie.getDomain(); // Save cookie into local store, or remove if expired if (!cookie.isExpired(new Date())) { cookies.put(name, cookie); } else { cookies.remove(name); } // Save cookie into persistent store SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie))); prefsWriter.commit(); }
@Override public List<Cookie> parse( final Header header, CookieOrigin origin) throws MalformedCookieException { if (header == null) { throw new IllegalArgumentException("Header may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) { throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'"); } origin = adjustEffectiveHost(origin); HeaderElement[] elems = header.getElements(); return createCookies(elems, origin); }
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"); } if (cookie.getVersion() > 0) { if (cookie instanceof SetCookie2) { return getStrict().match(cookie, origin); } else { return getObsoleteStrict().match(cookie, origin); } } else { return getCompat().match(cookie, origin); } }
/** * Validate cookie port attribute. If the Port attribute was specified * in header, the request port must be in cookie's port list. */ 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"); } int port = origin.getPort(); if (cookie instanceof ClientCookie && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) { if (!portMatch(port, cookie.getPorts())) { throw new CookieRestrictionViolationException( "Port attribute violates RFC 2965: " + "Request port not found in cookie's port list."); } } }
/** * 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(Locale.ENGLISH); 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()); return effectiveHostWithoutDomain.indexOf('.') == -1; }
public List<Header> formatCookies(final List<Cookie> cookies) { if (cookies == null) { throw new IllegalArgumentException("List of cookies may not be null"); } if (cookies.isEmpty()) { throw new IllegalArgumentException("List of cookies may not be empty"); } CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); buffer.append(SM.COOKIE); buffer.append(": "); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); if (i > 0) { buffer.append("; "); } buffer.append(cookie.getName()); String s = cookie.getValue(); if (s != null) { buffer.append("="); buffer.append(s); } } List<Header> headers = new ArrayList<Header>(1); headers.add(new BufferedHeader(buffer)); return headers; }
@Override public void addCookie(Cookie cookie) { String name = cookie.getName() + cookie.getDomain(); // Save cookie into local store, or remove if expired if (!cookie.isExpired(new Date())) { cookies.put(name, cookie); } else { cookies.remove(name); } // Save cookie into persistent store SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie))); prefsWriter.apply(); }
@Override public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { super.validate(cookie, origin); // Perform Netscape Cookie draft specific validation String host = origin.getHost(); String domain = cookie.getDomain(); if (host.contains(".")) { int domainParts = new StringTokenizer(domain, ".").countTokens(); if (isSpecialDomain(domain)) { if (domainParts < 2) { throw new CookieRestrictionViolationException("Domain attribute \"" + domain + "\" violates the Netscape cookie specification for " + "special domains"); } } else { if (domainParts < 3) { throw new CookieRestrictionViolationException("Domain attribute \"" + domain + "\" violates the Netscape cookie specification"); } } } }
public List<Header> formatCookies(final List<Cookie> cookies) { if (cookies == null) { throw new IllegalArgumentException("List of cookies may not be null"); } if (cookies.isEmpty()) { throw new IllegalArgumentException("List of cookies may not be empty"); } CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); buffer.append(SM.COOKIE); buffer.append(": "); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); if (i > 0) { buffer.append("; "); } buffer.append(cookie.getName()); buffer.append("="); String s = cookie.getValue(); if (s != null) { buffer.append(s); } } List<Header> headers = new ArrayList<Header>(1); headers.add(new BufferedHeader(buffer)); return headers; }
public List<Header> formatCookies(List<Cookie> cookies) { if (cookies == null) { throw new IllegalArgumentException("List of cookies may not be null"); } if (cookies.isEmpty()) { throw new IllegalArgumentException("List of cookies may not be empty"); } if (cookies.size() > 1) { // Create a mutable copy and sort the copy. cookies = new ArrayList<Cookie>(cookies); Collections.sort(cookies, PATH_COMPARATOR); } if (this.oneHeader) { return doFormatOneHeader(cookies); } else { return doFormatManyHeaders(cookies); } }
/** * Return a string suitable for sending in a <tt>"Cookie"</tt> header * as defined in RFC 2109 for backward compatibility with cookie version 0 * @param buffer The char array buffer to use for output * @param cookie The {@link Cookie} to be formatted as string * @param version The version to use. */ protected void formatCookieAsVer(final CharArrayBuffer buffer, final Cookie cookie, int version) { formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version); if (cookie.getPath() != null) { if (cookie instanceof ClientCookie && ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) { buffer.append("; "); formatParamAsVer(buffer, "$Path", cookie.getPath(), version); } } if (cookie.getDomain() != null) { if (cookie instanceof ClientCookie && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) { buffer.append("; "); formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version); } } }
/** * Construct a persistent cookie store. * * @param context Context to attach cookie store to */ public PersistentCookieStore(Context context) { cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0); cookies = new ConcurrentHashMap<String, Cookie>(); // Load any previously stored cookies into the store String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null); if (storedCookieNames != null) { String[] cookieNames = TextUtils.split(storedCookieNames, ","); for (String name : cookieNames) { String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null); if (encodedCookie != null) { Cookie decodedCookie = decodeCookie(encodedCookie); if (decodedCookie != null) { cookies.put(name, decodedCookie); } } } // Clear out expired cookies clearExpired(new Date()); } }
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(); String domain = cookie.getDomain(); if (domain == null) { return false; } if (host.equals(domain)) { return true; } if (!domain.startsWith(".")) { domain = '.' + domain; } return host.endsWith(domain) || host.equals(domain.substring(1)); }
@Override public boolean clearExpired(Date date) { boolean clearedAny = false; SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) { String name = entry.getKey(); Cookie cookie = entry.getValue(); if (cookie.isExpired(date)) { // Clear cookies from local store cookies.remove(name); // Clear cookies from persistent store prefsWriter.remove(COOKIE_NAME_PREFIX + name); // We've cleared at least one clearedAny = true; } } // Update names in persistent store if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); } prefsWriter.commit(); return clearedAny; }
public Cookie getCookie() { Cookie bestCookie = this.cookie; if (this.clientCookie != null) { return this.clientCookie; } return bestCookie; }
/** * Removes all of {@link Cookie cookies} in this HTTP state * that have expired by the specified {@link java.util.Date date}. * * @return true if any cookies were purged. * @see Cookie#isExpired(Date) */ @Override public synchronized boolean clearExpired(final Date date) { if (date == null) { return false; } boolean removed = false; for (final Iterator<Cookie> it = cookies.iterator(); it.hasNext(); ) { if (it.next().isExpired(date)) { it.remove(); removed = true; } } return removed; }
public String getOrFetchCsrf() throws ClientProtocolException, IOException { Optional<Cookie> checkCookie = getCsrfCookie(); if (!checkCookie.isPresent()) { sendRequest(new InstagramFetchHeadersRequest()); checkCookie = getCsrfCookie(); } return checkCookie.get().getValue(); }
public static void printCookies() { cookieStore = context.getCookieStore(); if (cookieStore == null) { return; } List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { System.out.println("key:" + cookie.getName() + " value:" + cookie.getValue() + " domain:" + cookie.getDomain() + cookie.getPath()); } }
public static String cookiegetSession() { System.out.println("cookie:"); cookieStore = context.getCookieStore(); if (cookieStore == null) { return null; } List<Cookie> cookies = cookieStore.getCookies(); return cookies.get(0).getValue(); }
/** * Extract the sessionId from the response cookies * * @param context the context holding the cookies * * @return the sessionId if found * * @throws IOException */ private Optional<String> extractSessionId(HttpClientContext context) { CookieStore cookieStore = context.getCookieStore(); Set<String> jSessionCookies = cookieStore.getCookies().stream() .filter(c -> c.getName().equals("JSESSIONID")) .map(Cookie::getValue).collect(Collectors.toSet()); Iterator<String> it = jSessionCookies.iterator(); if (!it.hasNext()) { return Optional.empty(); } else { return Optional.of(it.next()); } }
@Override protected HttpResponse makeHttpRequest(HttpEntity entity, long startTime) { if (entity != null) { requestBuilder.setEntity(entity); requestBuilder.setHeader(entity.getContentType()); } HttpUriRequest httpRequest = requestBuilder.build(); CloseableHttpClient client = clientBuilder.build(); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(URI_CONTEXT_KEY, getRequestUri()); CloseableHttpResponse httpResponse; byte[] bytes; try { httpResponse = client.execute(httpRequest, context); HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity == null || responseEntity.getContent() == null) { bytes = new byte[0]; } else { InputStream is = responseEntity.getContent(); bytes = FileUtils.toBytes(is); } } catch (Exception e) { throw new RuntimeException(e); } long responseTime = getResponseTime(startTime); HttpResponse response = new HttpResponse(responseTime); response.setUri(getRequestUri()); response.setBody(bytes); response.setStatus(httpResponse.getStatusLine().getStatusCode()); for (Cookie c : cookieStore.getCookies()) { com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue()); cookie.put(DOMAIN, c.getDomain()); cookie.put(PATH, c.getPath()); if (c.getExpiryDate() != null) { cookie.put(EXPIRES, c.getExpiryDate().getTime() + ""); } cookie.put(PERSISTENT, c.isPersistent() + ""); cookie.put(SECURE, c.isSecure() + ""); response.addCookie(cookie); } cookieStore.clear(); // we rely on the StepDefs for cookie 'persistence' for (Header header : httpResponse.getAllHeaders()) { response.addHeader(header.getName(), header.getValue()); } return response; }
public static String getCookieValue(List<Cookie> cookies, String cookieName){ Cookie cookie = getCookie(cookies, cookieName); if(cookie == null){ return null; } return cookie.getValue(); }
public static Cookie getCookie(List<Cookie> cookies, String cookieName){ if(cookies == null || cookieName == null){ return null; } for(Cookie cookie : cookies){ if(cookieName.equals(cookie.getName())){ return cookie; } } return null; }
@Test public void testGetCookie(){ List<Cookie> cookies = new ArrayList<>(); cookies.add(shortBreadCookie); cookies.add(sandwichCookie); Cookie cookie = ApacheCookieTool.getCookie(cookies, shortBreadCookie.getName()); Assert.assertTrue(shortBreadCookie.getName().equals(cookie.getName())); }