Example usage for org.apache.http.client CookieStore getCookies

List of usage examples for org.apache.http.client CookieStore getCookies

Introduction

In this page you can find the example usage for org.apache.http.client CookieStore getCookies.

Prototype

List<Cookie> getCookies();

Source Link

Document

Returns all cookies contained in this store.

Usage

From source file:de.koczewski.maxapi.RequestExecutor.java

public String getCookieValue(String name) {
    CookieStore cookieStore = httpClient.getCookieStore();
    for (Cookie cookie : cookieStore.getCookies()) {
        if (name.equals(cookie.getName()))
            return cookie.getValue();
    }// www  .j  av  a  2s. c o  m
    return null;
}

From source file:thiru.in.basicauthwebview.ShowWebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_web_view);

    // Initialize the Cookie Manager
    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    String url = "http://auth.thiru.in/";
    // Call the REST Service to Authenticate
    // This is sample app, the app can have a login form, accept input, encode the
    // id and passowrd using Base64 for Validating
    AsyncTask<String, Void, CookieStore> cookieStoreTask = new Authenticate(this).execute(url + "app-auth",
            "ZGVtbzpkZW1v"); //Base64 Encoded for demo:demo

    try {//from  w w  w . j  a  v  a2 s  . c om
        cookieManager.removeAllCookie();
        CookieStore cookieStore = cookieStoreTask.get();
        List<Cookie> cookies = cookieStore.getCookies();
        // If the User id and password is wrong, the cookie store will not have any cookies
        // And the page will display 403 Access Denied
        for (Cookie cookie : cookies) {
            Log.i("Cookie", cookie.getName() + " ==> " + cookie.getValue());
            // Add the REST Service Cookie Responses to Cookie Manager to make it
            // Available for the WebViewClient
            cookieManager.setCookie(url, cookie.getName() + "=" + cookie.getValue());
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new WebViewClient());
    mWebView.loadUrl(url);
}

From source file:com.github.irib_examples.Act_Cookies.java

public Cookie getCookie(CookieStore cs, String cookieName) {
    Cookie ret = null;//from  www  .  j  a va  2  s  .  com

    List<Cookie> l = cs.getCookies();
    for (Cookie c : l) {
        if (c.getName().equals(cookieName)) {
            ret = c;
            break;
        }
    }

    return ret;
}

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return our session cookie; {@code null} if it doesn't exist
 *///w  ww . j  av  a 2 s  .c o m
@Nullable
protected Cookie getSessionCookie(CookieStore cookieStore) {
    for (Cookie cookie : cookieStore.getCookies()) {
        if (DEFAULT_SESSION_COOKIE_NAME.equals(cookie.getName())) {
            return cookie;
        }
    }
    return null;
}

From source file:io.cloudslang.content.httpclient.build.CookieStoreBuilderTest.java

@Test
public void buildCookieStore() {
    SerializableSessionObject sessionObjectHolder = new SerializableSessionObject();
    CookieStore cookieStore = cookieStoreBuilder.setCookieStoreSessionObject(sessionObjectHolder)
            .buildCookieStore();// w ww . j a v a  2 s. c  o  m
    assertNotNull(cookieStore);
    assertEquals(0, cookieStore.getCookies().size());
}

From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.java

/**
 * Syncs all cookies from ExoConnectionUtils cookieStore from Apache's
 * HttpClient to HttpURLConnection.//from  w  ww.  j a v a2s  .c  o m
 * 
 * @param manager the CookieManager in which to store the retrieved cookies
 */
private void syncCookies(CookieManager manager) {
    CookieStore store = ExoConnectionUtils.cookiesStore;
    if (store == null)
        return;

    for (Cookie cookie : store.getCookies()) {
        HttpCookie c = new HttpCookie(cookie.getName(), cookie.getValue());
        c.setDomain(cookie.getDomain());
        c.setPath(cookie.getPath());
        c.setVersion(cookie.getVersion());
        String url = AccountSetting.getInstance().getDomainName() + "/" + cookie.getPath();
        try {
            manager.getCookieStore().add(new URI(url), c);
        } catch (URISyntaxException e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Executes the authentication to the Jaspersoft community in order to
 * retrieve the session cookie to use later for all other operations.
 * /*  w  w w.  j ava  2  s  .  c om*/
 * @param httpclient
 *            the http client
 * 
 * @param cookieStore
 *            the Cookie Store instance
 * @param username
 *            the community user name (or email)
 * @param password
 *            the community user password
 * @return the authentication cookie if able to retrieve it,
 *         <code>null</code> otherwise
 * @throws CommunityAPIException
 */
public static Cookie getAuthenticationCookie(CloseableHttpClient httpclient, CookieStore cookieStore,
        String username, String password) throws CommunityAPIException {

    try {
        HttpPost loginPOST = new HttpPost(CommunityConstants.LOGIN_URL);
        EntityBuilder loginEntity = EntityBuilder.create();
        loginEntity.setText("{ \"username\": \"" + username + "\", \"password\":\"" + password + "\" }"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        loginEntity.setContentType(ContentType.create(CommunityConstants.JSON_CONTENT_TYPE));
        loginEntity.setContentEncoding(CommunityConstants.REQUEST_CHARSET);
        loginPOST.setEntity(loginEntity.build());

        CloseableHttpResponse resp = httpclient.execute(loginPOST);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());
        if (HttpStatus.SC_OK == httpRetCode) {
            // Can proceed
            List<Cookie> cookies = cookieStore.getCookies();
            Cookie authCookie = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().startsWith("SESS")) { //$NON-NLS-1$
                    authCookie = cookie;
                    break;
                }
            }
            return authCookie;
        } else if (HttpStatus.SC_UNAUTHORIZED == httpRetCode) {
            // Unauthorized... wrong username or password
            CommunityAPIException unauthorizedEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_WrongUsernamePasswordError);
            unauthorizedEx.setHttpStatusCode(httpRetCode);
            unauthorizedEx.setResponseBodyAsString(responseBodyAsString);
            throw unauthorizedEx;
        } else {
            // Some other problem occurred
            CommunityAPIException generalEx = new CommunityAPIException(
                    Messages.RESTCommunityHelper_AuthInfoProblemsError);
            generalEx.setHttpStatusCode(httpRetCode);
            generalEx.setResponseBodyAsString(responseBodyAsString);
            throw generalEx;
        }
    } catch (UnsupportedEncodingException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_EncodingNotValidError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_PostMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_AuthenticationError, e);
    }
}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

private void toCookieManager(URI uri, CookieStore cs, CookieManager cm) {
    cm.getCookieStore().removeAll();/*from w ww .j  av  a  2 s . c o  m*/
    for (Cookie c : cs.getCookies()) {
        cm.getCookieStore().add(uri, toHttpCookie(c));
    }
}

From source file:com.liato.bankdroid.WebViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);/*from   w w  w .j  a v  a 2 s.co m*/
    this.addTitleButton(R.drawable.title_icon_back, "back", this);
    this.addTitleButton(R.drawable.title_icon_forward, "forward", this);
    this.addTitleButton(R.drawable.title_icon_refresh, "refresh", this);
    this.setTitleButtonEnabled("forward", false);
    this.setTitleButtonEnabled("back", false);
    this.setTitleButtonEnabled("refresh", false);

    final CookieSyncManager csm = CookieSyncManager.createInstance(this);
    mWebView = (WebView) findViewById(R.id.wvBank);
    mWebView.setBackgroundColor(0);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUserAgentString(Urllib.DEFAULT_USER_AGENT);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgressBar(progress);
            if (progress == 100) {
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                    public void run() {
                        activity.hideProgressBar();
                    }
                };
                // Let the progress bar hit 100% before we hide it.
                handler.postDelayed(runnable, 100);

            } else if (mFirstPageLoaded) {
                activity.showProgressBar();
            }
        }
    });
    mWebView.setWebViewClient(new BankWebViewClient());
    String preloader = "Error...";
    try {
        preloader = IOUtils.toString(getResources().openRawResource(R.raw.loading));
        preloader = String.format(preloader, "", // Javascript function
                "" // HTML
        );
    } catch (NotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", preloader, "text/html", "utf-8", null);

    Bundle extras = getIntent().getExtras();
    final long bankId = extras.getLong("bankid", -1);
    //final long bankId = -1;
    if (bankId >= 0) {
        Runnable generateLoginPage = new Runnable() {
            public void run() {
                Bank bank = BankFactory.bankFromDb(bankId, WebViewActivity.this, false);
                SessionPackage loginPackage = bank.getSessionPackage(WebViewActivity.this);
                CookieStore cookieStore = loginPackage.getCookiestore();
                if ((cookieStore != null) && !cookieStore.getCookies().isEmpty()) {
                    CookieManager cookieManager = CookieManager.getInstance();
                    String cookieString;
                    for (Cookie cookie : cookieStore.getCookies()) {
                        cookieString = String.format("%s=%s;%spath=%s; domain=%s;", cookie.getName(),
                                cookie.getValue(),
                                cookie.getExpiryDate() == null ? ""
                                        : "expires=" + cookie.getExpiryDate() + "; ",
                                cookie.getPath() == null ? "/" : cookie.getPath(), cookie.getDomain());
                        cookieManager.setCookie(cookie.getDomain(), cookieString);
                    }
                    csm.sync();
                }
                mWebView.loadDataWithBaseURL("what://is/this/i/dont/even", loginPackage.getHtml(), "text/html",
                        "utf-8", null);
            }
        };
        new Thread(generateLoginPage).start();
    }
}

From source file:org.archive.modules.fetcher.AbstractCookieStore.java

public boolean isCookieCountMaxedForDomain(String domain) {
    CookieStore cookieStore = cookieStoreFor(normalizeHost(domain));

    return (cookieStore != null && cookieStore.getCookies().size() >= MAX_COOKIES_FOR_DOMAIN);
}