Example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore

List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCookieStore BasicCookieStore.

Prototype

public BasicCookieStore() 

Source Link

Usage

From source file:com.synopsys.integration.blackduck.rest.CredentialsBlackDuckHttpClient.java

@Override
public void populateHttpClientBuilder(HttpClientBuilder httpClientBuilder,
        RequestConfig.Builder defaultRequestConfigBuilder) {
    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    defaultRequestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);
}

From source file:edu.mit.scratch.ScratchSession.java

public void logout() throws ScratchUserException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();//from w w w  .  j  a va2s .  c  o m

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                    + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
            .setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject loginObj = new JSONObject();
    loginObj.put("csrftoken", this.getCSRFToken());
    try {
        final HttpUriRequest logout = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/logout/")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8")
                .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("X-CSRFToken", this.getCSRFToken()).setEntity(new StringEntity(loginObj.toString()))
                .build();
        resp = httpClient.execute(logout);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }

    this.session_id = null;
    this.token = null;
    this.expires = null;
    this.username = null;
}

From source file:org.alfresco.po.share.util.FileDownloader.java

/**
 * Loads the cookies from WebDriver to mimic the browser cookie state
 * @return {@link BasicCookieStore} current state
 *///  www.  ja  v a  2s  .  co  m
private BasicCookieStore getCookies() {

    BasicCookieStore mimicWebDriverCookie = new BasicCookieStore();
    Set<Cookie> cookies = driver.manage().getCookies();

    for (Cookie seleniumCookie : cookies) {
        BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(),
                seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        mimicWebDriverCookie.addCookie(duplicateCookie);
    }
    return mimicWebDriverCookie;
}

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

@Override
protected CookieStore doInBackground(String... data) {
    String url = data[0];/*from  w  w w .  j  a  va2  s  .  c  o m*/
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("token", data[1]));
    DefaultHttpClient httpClient = new DefaultHttpClient();

    BasicCookieStore cookieStore = new BasicCookieStore();
    httpClient.setCookieStore(cookieStore);

    HttpPost httpPost = new HttpPost(url);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            List<Cookie> cookies = cookieStore.getCookies();

            for (Cookie cookie : cookies) {
                Log.i("Cookie", cookie.getName() + " ==> " + cookie.getValue());
            }
        } else {
            Log.i("Authenticate", "Invalid user and password combination");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return cookieStore;
}

From source file:com.phonty.improved.DirectionCost.java

public DirectionCost(String url, Context _context) {
    context = _context;/* w w w .  ja  va2s .  co  m*/
    BasicHttpParams params = new BasicHttpParams();
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 4711));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    client = new PhontyHttpClient(cm, params, context);
    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(Login.SESSION_COOKIE);
    client.setCookieStore(cookieStore);
    APIURL = url;
    httppost = new HttpPost(APIURL);
}

From source file:com.cognifide.qa.bb.aem.AemAuthCookieFactory.java

/**
 * This method provides browser cookie for authenticating user to AEM instance
 *
 * @param url      URL to AEM instance, like http://localhost:4502
 * @param login    Username to use/*from   w  ww  . j  a v a 2s  . co m*/
 * @param password Password to use
 * @return Cookie for selenium WebDriver.
 */
public Cookie getCookie(String url, String login, String password) {
    if (!cookieJar.containsKey(url)) {
        HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check");

        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8"));
        nameValuePairs.add(new BasicNameValuePair("j_username", login));
        nameValuePairs.add(new BasicNameValuePair("j_password", password));
        nameValuePairs.add(new BasicNameValuePair("j_validate", "true"));

        CookieStore cookieStore = new BasicCookieStore();
        HttpClientContext context = HttpClientContext.create();

        if ("true".equals(properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE))) {
            addProxyCookie(cookieStore);
        }

        context.setCookieStore(cookieStore);

        try {
            loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context);
            loginResponse.close();
        } catch (IOException e) {
            LOG.error("Can't get AEM authentication cookie", e);
        } finally {
            loginPost.reset();
        }
        Cookie cookie = findAuthenticationCookie(cookieStore.getCookies());
        if (cookie != null) {
            cookieJar.put(url, cookie);
        }
    }
    return cookieJar.get(url);
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthManager.java

/**
 * EGet the authenfication by executing the defined requests sequence.
 *
 * @throws IOException//from w ww. j  a  v a2  s  . c  om
 * @throws ClientProtocolException
 */
public ExitStatus authentificate() throws ClientProtocolException, IOException {
    authCookie = null;

    if (firstRequest != null) {

        final CookieStore cookieStore = new BasicCookieStore();
        client = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setRedirectStrategy(new LaxRedirectStrategy()).useSystemProperties().build();

        lastResponse = firstRequest.executeSequence(client);

        final List<Cookie> cookies = cookieStore.getCookies();
        final StringBuilder strBuff = new StringBuilder();
        for (final Cookie cookie : cookies) {
            strBuff.append(cookie.getName());
            strBuff.append("=");
            strBuff.append(cookie.getValue());
            strBuff.append(";");
        }

        authCookie = strBuff.toString();
    }

    return ExitStatus.COMPLETED;
}

From source file:fedroot.dacs.http.DacsClientContext.java

public DacsClientContext(HttpParams httpParams) {

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    if (httpParams.getParameter(ClientPNames.COOKIE_POLICY) == null) {
        httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    }//from w  w  w .  j  ava2  s  .c  om
    httpClient = new DefaultHttpClient(cm, httpParams);

    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:org.mobicents.slee.ra.httpclient.nio.ra.HttpClientNIORequestActivityImpl.java

private HttpContext processHttpContext(HttpContext context) {
    // Maintains HttpSession on server side
    if (context == null) {
        context = new BasicHttpContext();

    }/*from   w  w w. j a v  a 2s .c o  m*/
    if (context.getAttribute(ClientContext.COOKIE_STORE) == null) {
        BasicCookieStore cookieStore = new BasicCookieStore();
        context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }
    return context;
}

From source file:com.law.commons.util.MyHttpWrapper.java

/**
 * Apply post http request to the back server.
 *
 * @return boolean success/fail//from  w  w w .  ja v a 2s.c o m
 */
protected boolean doPost() {
    boolean ret = false;
    try {
        BasicCookieStore cookieStore = new BasicCookieStore();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setDefaultHeaders(this.headers).build();

        HttpEntity entity = new UrlEncodedFormEntity(this.params, "UTF-8");
        HttpPost request = new HttpPost(this.websrvurl);
        request.setEntity(entity);
        //            logger.info("???:"+DateUtil.getNowOfNODIV());
        CloseableHttpResponse response = httpclient.execute(request);
        //            logger.info("???:"+DateUtil.getNowOfNODIV());
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity rentity = response.getEntity();
            String sEntity = EntityUtils.toString(rentity);
            // parse json here.
            JSONObject jsonObject = JSONObject.fromObject(sEntity);
            String res = jsonObject.getString("response").trim();
            if (res.equals("OK")) {
                ret = true;
            }
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {

    }
    return ret;
}