cz.msebera.android.httpclient.cookie.Cookie Java Examples

The following examples show how to use cz.msebera.android.httpclient.cookie.Cookie. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP POST request with cookies which are defined in hashmap
 *
 * @param context
 * @param url
 * @param hashMap
 * @param responseHandler
 */
public static void postUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) {
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    if (BasicUtils.judgeNotNull(hashMap)) {
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            Cookie cookie = new BasicClientCookie(key.toString(), value.toString());
            myCookieStore.addCookie(cookie);
        }
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.setCookieStore(myCookieStore);
    client.post(getAbsoluteUrl(url), responseHandler);
}
 
Example #2
Source File: HttpUtilsAsync.java    From UltimateAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a HTTP GET request with cookies which are defined in hashmap
 *
 * @param context
 * @param url
 * @param hashMap
 * @param responseHandler
 */
public static void getUseCookie(Context context, String url, HashMap hashMap, AsyncHttpResponseHandler responseHandler) {
    PersistentCookieStore myCookieStore = new PersistentCookieStore(context);
    if (BasicUtils.judgeNotNull(hashMap)) {
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            Cookie cookie = new BasicClientCookie(key.toString(), value.toString());
            myCookieStore.addCookie(cookie);
        }
    }
    AsyncHttpClient client = new AsyncHttpClient();
    client.setCookieStore(myCookieStore);
    client.get(getAbsoluteUrl(url), responseHandler);
}
 
Example #3
Source File: CloudflareChecker.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
static boolean isClearanceCookie(Cookie cookie, String url, String requiredCookieName) {
    try {
        String cookieName = cookie.getName();
        String cookieDomain = cookie.getDomain();
        if (!cookieDomain.startsWith(".")) {
            cookieDomain = "." + cookieDomain;
        }
        
        String urlCookie = "." + Uri.parse(url).getHost();
        if (cookieName.equals(requiredCookieName) && cookieDomain.equalsIgnoreCase(urlCookie)) {
            return true;
        }
    } catch (Exception e) {
        Logger.e(TAG, e);
    }
    return false;
}
 
Example #4
Source File: CloudflareChecker.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Пройти анти-ддос проверку cloudflare
 * @param exception Cloudflare исключение
 * @param httpClient HTTP клиент
 * @param task отменяемая задача
 * @param activity активность, в контексте которого будет запущен WebView (webkit)
 * @return полученная cookie или null, если проверка не прошла по таймауту, или проверка уже проходит в другом потоке
 */
public Cookie checkAntiDDOS(CloudflareException exception, HttpClient httpClient, CancellableTask task, Activity activity) {
    if (exception.isRecaptcha()) throw new IllegalArgumentException();
    
    HttpHost proxy = null;
    if (httpClient instanceof ExtendedHttpClient) {
        proxy = ((ExtendedHttpClient) httpClient).getProxy();
    } else if (httpClient != null) {
        try {
            proxy = ConnRouteParams.getDefaultProxy(httpClient.getParams());
        } catch (Exception e) { /*ignore*/ }
    }
    if (proxy != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (httpClient instanceof ExtendedHttpClient) {
            return InterceptingAntiDDOS.getInstance().check(exception, (ExtendedHttpClient) httpClient, task, activity);
        } else {
            throw new IllegalArgumentException(
                    "cannot run anti-DDOS checking with proxy settings; http client is not instance of ExtendedHttpClient");
        }
    } else {
        return checkAntiDDOS(exception, proxy, task, activity);
    }
}
 
Example #5
Source File: CloudflareChecker.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
static void removeCookie(CookieStore store, String name) {
    boolean flag = false;
    for (Cookie cookie : store.getCookies()) {
        if (cookie.getName().equals(name)) {
            if (cookie instanceof SetCookie) {
                flag = true;
                ((SetCookie) cookie).setExpiryDate(new Date(0));
            } else {
                Logger.e(TAG, "cannot remove cookie (object does not implement SetCookie): " + cookie.toString());
            }
        }
    }
    if (flag) store.clearExpired(new Date());
}
 
Example #6
Source File: CookieStoreHelper.java    From BaiduPanApi-Java with MIT License 5 votes vote down vote up
public static String get(CookieStore cookieStore, String key){
    List<Cookie> cookieList  = cookieStore.getCookies();
    for(Cookie cookie:cookieList){
        if(cookie.getName().equals(key)){
            return cookie.getValue();
        }
    }
    return null;
}
 
Example #7
Source File: MakabaModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveCookie(Cookie cookie) {
    super.saveCookie(cookie);
    if (cookie != null && cookie.getName().equals(USERCODE_COOKIE_NAME)) {
        preferences.edit().
                putString(getSharedKey(PREF_KEY_USERCODE_COOKIE_DOMAIN), cookie.getDomain()).
                putString(getSharedKey(PREF_KEY_USERCODE_COOKIE_VALUE), cookie.getValue()).commit();
    }
}
 
Example #8
Source File: PonyachModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private void savePhpCookies() {
    for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
        if (cookie.getName().equalsIgnoreCase(PHPSESSION_COOKIE_NAME) && cookie.getDomain().contains(getUsingDomain())) {
            preferences.edit().putString(getSharedKey(PREF_KEY_PHPSESSION_COOKIE), cookie.getValue()).commit();
        }
    }
}
 
Example #9
Source File: MikubaModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveCookie(Cookie cookie) {
    super.saveCookie(cookie);
    if (cookie != null) {
        saveCookieToPreferences(cookie);
    }
}
 
Example #10
Source File: Chan410Module.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
private void saveFaptchaCookies() {
    JSONObject savedCookies = new JSONObject();
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().length() <= 3 && Chan410Boards.ALL_BOARDS_SET.contains(cookie.getName())) {
            savedCookies.put(cookie.getName(), cookie.getValue());
        }
    }
    preferences.edit().putString(getSharedKey(PREF_KEY_FAPTCHA_COOKIES), savedCookies.toString()).commit();
}
 
Example #11
Source File: DobroModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveCookie(Cookie cookie) {
    if (cookie != null) {
        httpClient.getCookieStore().addCookie(cookie);
        saveHanabiraCookie();
    }
}
 
Example #12
Source File: CloudflareChecker.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Проверить рекапчу cloudflare, получить cookie
 * @param exception Cloudflare исключение
 * @param httpClient HTTP клиент
 * @param task отменяемая задача
 * @param challenge challenge рекапчи
 * @param recaptchaAnswer ответ на рекапчу
 * @return полученная cookie или null, если проверка не прошла
 */
public Cookie checkRecaptcha(CloudflareException exception, ExtendedHttpClient httpClient, CancellableTask task, String url) {
    if (!exception.isRecaptcha()) throw new IllegalArgumentException("wrong type of CloudflareException");
    HttpResponseModel responseModel = null;
    try {
        HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setNoRedirect(false).build();
        CookieStore cookieStore = httpClient.getCookieStore();
        removeCookie(cookieStore, exception.getRequiredCookieName());
        responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
        for (int i = 0; i < 3  && responseModel.statusCode == 400; ++i) {
            Logger.d(TAG, "HTTP 400");
            responseModel.release();
            responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
        }
        for (Cookie cookie : cookieStore.getCookies()) {
            if (isClearanceCookie(cookie, url, exception.getRequiredCookieName())) {
                Logger.d(TAG, "Cookie found: " + cookie.getValue());
                return cookie;
            }
        }
        Logger.d(TAG, "Cookie is not found");
    } catch (Exception e) {
        Logger.e(TAG, e);
    } finally {
        if (responseModel != null) {
            responseModel.release();
        }
    }
    return null;
}
 
Example #13
Source File: CloudflareChanModule.java    From Overchan-Android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveCookie(Cookie cookie) {
    super.saveCookie(cookie);
    if (cookie != null) {
        if (canCloudflare() && cookie.getName().equals(CLOUDFLARE_COOKIE_NAME)) {
            preferences.edit().
                    putString(getSharedKey(PREF_KEY_CLOUDFLARE_COOKIE_VALUE), cookie.getValue()).
                    putString(getSharedKey(PREF_KEY_CLOUDFLARE_COOKIE_DOMAIN), cookie.getDomain()).commit();
        }
    }
}
 
Example #14
Source File: HtmlUnitDomainHandler.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    String domain = cookie.getDomain();
    if (domain == null) {
        return false;
    }

    final int dotIndex = domain.indexOf('.');
    if (dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
        final String host = origin.getHost();
        domain = domain.toLowerCase(Locale.ROOT);
        if (browserVersion_.hasFeature(HTTP_COOKIE_REMOVE_DOT_FROM_ROOT_DOMAINS)) {
            domain = domain.substring(1);
        }
        if (host.equals(domain)) {
            return true;
        }
        return false;
    }

    if (dotIndex == -1
            && !HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN.equalsIgnoreCase(domain)) {
        try {
            InetAddress.getByName(domain);
        }
        catch (final UnknownHostException e) {
            return false;
        }
    }

    return super.match(cookie, origin);
}
 
Example #15
Source File: HtmlUnitBrowserCompatCookieSpec.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
@Override
public List<Header> formatCookies(final List<Cookie> cookies) {
    Collections.sort(cookies, COOKIE_COMPARATOR);

    final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
    buffer.append(SM.COOKIE);
    buffer.append(": ");
    for (int i = 0; i < cookies.size(); i++) {
        final Cookie cookie = cookies.get(i);
        if (i > 0) {
            buffer.append("; ");
        }
        final String cookieName = cookie.getName();
        final String cookieValue = cookie.getValue();
        if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
            HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(
                    buffer,
                    new BasicHeaderElement(cookieName, cookieValue),
                    false);
        }
        else {
            // Netscape style cookies do not support quoted values
            buffer.append(cookieName);
            buffer.append("=");
            if (cookieValue != null) {
                buffer.append(cookieValue);
            }
        }
    }
    final List<Header> headers = new ArrayList<>(1);
    headers.add(new BufferedHeader(buffer));
    return headers;
}
 
Example #16
Source File: HtmlUnitPathHandler.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    CookieOrigin newOrigin = origin;
    String targetpath = origin.getPath();
    if (browserVersion_.hasFeature(HTTP_COOKIE_EXTRACT_PATH_FROM_LOCATION) && !targetpath.isEmpty()) {
        final int lastSlashPos = targetpath.lastIndexOf('/');
        if (lastSlashPos > 1 && lastSlashPos < targetpath.length()) {
            targetpath = targetpath.substring(0, lastSlashPos);
            newOrigin = new CookieOrigin(origin.getHost(), origin.getPort(), targetpath, origin.isSecure());
        }
    }

    return super.match(cookie, newOrigin);
}
 
Example #17
Source File: AbstractChanModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void saveCookie(Cookie cookie) {
    if (cookie != null) {
        httpClient.getCookieStore().addCookie(cookie);
    }
}
 
Example #18
Source File: HtmlUnitPathHandler.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
    // nothing, browsers seem not to perform any validation
}
 
Example #19
Source File: InterceptingAntiDDOS.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
/** Метод anti-DDOS проверки, все запросы перехватываются из webview в httpclient (для использования с прокси-сервером на API >= 11) */
Cookie check(final CloudflareException exception, final ExtendedHttpClient httpClient, final CancellableTask task, final Activity activity) {
    synchronized (lock) {
        if (processing) return null;
        processing = true;
    }
    processing2 = true;
    currentCookie = null;
    
    final HttpRequestModel rqModel = HttpRequestModel.DEFAULT_GET;
    final CookieStore cookieStore = httpClient.getCookieStore();
    CloudflareChecker.removeCookie(cookieStore, exception.getRequiredCookieName());
    final ViewGroup layout = (ViewGroup)activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            HttpResponseModel responseModel = null;
            try {
                responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                for (int i = 0; i < 3  && responseModel.statusCode == 400; ++i) {
                    Logger.d(TAG, "HTTP 400");
                    responseModel.release();
                    responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
                }
                for (Cookie cookie : cookieStore.getCookies()) {
                    if (CloudflareChecker.isClearanceCookie(cookie, url, exception.getRequiredCookieName())) {
                        Logger.d(TAG, "Cookie found: " + cookie.getValue());
                        currentCookie = cookie;
                        processing2 = false;
                        return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("cookie received".getBytes()));
                    }
                }
                BufOutputStream output = new BufOutputStream();
                IOUtils.copyStream(responseModel.stream, output);
                return new WebResourceResponse(null, null, output.toInputStream());
            } catch (Exception e) {
                Logger.e(TAG, e);
            } finally {
                if (responseModel != null) responseModel.release();
            }
            return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("something wrong".getBytes()));
        }
    };
    
    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > CloudflareChecker.TIMEOUT) {
            processing2 = false;
        }
    }
    
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                processing = false;
            }
        }
    });
    return currentCookie;
}
 
Example #20
Source File: DobroModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private void saveHanabiraCookie() {
    for (Cookie cookie : httpClient.getCookieStore().getCookies())
        if (cookie.getName().equals(HANABIRA_COOKIE_NAME))
            preferences.edit().putString(getSharedKey(PREF_KEY_HANABIRA_COOKIE), cookie.getValue()).commit();
}
 
Example #21
Source File: HtmlUnitHttpOnlyHandler.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    return true;
}
 
Example #22
Source File: HtmlUnitHttpOnlyHandler.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
@Override
public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
    // nothing
}
 
Example #23
Source File: MikubaModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private void saveCookiesToPreferences() {
    for (Cookie cookie : httpClient.getCookieStore().getCookies()) saveCookieToPreferences(cookie);
}
 
Example #24
Source File: MikubaModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private void saveCookieToPreferences(Cookie cookie) {
    if (cookie.getName().equals(SESSION_COOKIE_NAME)) {
        preferences.edit().putString(getSharedKey(PREF_KEY_SESSION_COOKIE), cookie.getValue()).commit();
    }
}
 
Example #25
Source File: HtmlUnitCookieStore.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized List<Cookie> getCookies() {
    return com.gargoylesoftware.htmlunit.util.Cookie.toHttpClient(manager_.getCookies());
}
 
Example #26
Source File: HtmlUnitCookieStore.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public synchronized void addCookie(final Cookie cookie) {
    manager_.addCookie(new com.gargoylesoftware.htmlunit.util.Cookie((ClientCookie) cookie));
}
 
Example #27
Source File: MakabaModule.java    From Overchan-Android with GNU General Public License v3.0 4 votes vote down vote up
private void saveUsercodeCookie() {
    for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
        if (cookie.getName().equals(USERCODE_COOKIE_NAME) && cookie.getDomain().contains(domain)) saveCookie(cookie);
    }
}
 
Example #28
Source File: HttpChanModule.java    From Overchan-Android with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Добавить Cookie к HTTP клиенту и сохранить его в параметрах, если это предусмотрено конкретной имиджбордой (напр. в случае Cloudflare)
 */
void saveCookie(Cookie cookie);