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:net.vexelon.mobileops.MTLClient.java

/**
 * Initialize Http Client/*from   w w w  . jav  a  2  s .  co m*/
 */
private void initHttpClient() {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.TRUE);
    params.setParameter(CoreProtocolPNames.USER_AGENT, HTTP_USER_AGENT);
    //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
    httpClient = new DefaultHttpClient(params);

    httpCookieStore = new BasicCookieStore();
    httpClient.setCookieStore(httpCookieStore);
}

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

protected static JSONObject getStatisticsJSONObject() throws ScratchStatisticalException {
    try {//w w w.ja v  a2  s. c o m
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(debug);
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/statistics/data/daily/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchStatisticalException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        return new JSONObject(result.toString().trim());
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchStatisticalException();
    }
}

From source file:gmusic.api.comm.ApacheConnector.java

public ApacheConnector() {
    HttpParams params = new BasicHttpParams();
    params.removeParameter("User-Agent");
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    // HttpConnectionParams.setConnectionTimeout(params, 150000);
    // HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:gmusic.api.api.comm.ApacheConnector.java

public ApacheConnector() {
    final HttpParams params = new BasicHttpParams();
    params.removeParameter("User-Agent");
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    // HttpConnectionParams.setConnectionTimeout(params, 150000);
    // HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:de.tntinteractive.portalsammler.engine.FileDownloader.java

/**
 * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state
 *//*from  ww w. ja v  a  2s . c  o  m*/
private BasicCookieStore mimicCookieState(final Set<Cookie> seleniumCookieSet) {
    final BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore();
    for (final Cookie seleniumCookie : seleniumCookieSet) {
        final BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(),
                seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        mimicWebDriverCookieStore.addCookie(duplicateCookie);
    }

    return mimicWebDriverCookieStore;
}

From source file:org.oss.bonita.utils.bonita.RestClient.java

public void loginAs(String username, String password) {

    try {/*from w ww  . j a  v  a  2 s .  c o m*/

        CookieStore cookieStore = new BasicCookieStore();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        String loginURL = "/loginservice";

        // If you misspell a parameter you will get a HTTP 500 error
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("username", username));
        urlParameters.add(new BasicNameValuePair("password", password));
        urlParameters.add(new BasicNameValuePair("redirect", "false"));

        // UTF-8 is mandatory otherwise you get a NPE
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, "utf-8");
        executePostRequest(loginURL, entity);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }

}

From source file:org.apache.sling.testing.clients.interceptors.StickyCookieInterceptor.java

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();//from  w  w w.  j  a va 2 s .c  o m
        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);
}

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

public static ScratchSession createSession(final String username, String password)
        throws ScratchLoginException {
    try {/*from w ww .j a va  2 s .  com*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation
                .build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/")
                .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        resp = httpClient.execute(csrf);
        resp.close();

        String csrfToken = null;
        for (final Cookie c : cookieStore.getCookies())
            if (c.getName().equals("scratchcsrftoken"))
                csrfToken = c.getValue();

        final JSONObject loginObj = new JSONObject();
        loginObj.put("username", username);
        loginObj.put("password", password);
        loginObj.put("captcha_challenge", "");
        loginObj.put("captcha_response", "");
        loginObj.put("embed_captcha", false);
        loginObj.put("timezone", "America/New_York");
        loginObj.put("csrfmiddlewaretoken", csrfToken);
        final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/")
                .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", csrfToken).setEntity(new StringEntity(loginObj.toString())).build();
        resp = httpClient.execute(login);
        password = null;
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ = new JSONObject(
                result.toString().substring(1, result.toString().length() - 1));
        if ((int) jsonOBJ.get("success") != 1)
            throw new ScratchLoginException();
        String ssi = null;
        String sct = null;
        String e = null;
        final Header[] headers = resp.getAllHeaders();
        for (final Header header : headers)
            if (header.getName().equals("Set-Cookie")) {
                final String value = header.getValue();
                final String[] split = value.split(Pattern.quote("; "));
                for (final String s : split) {
                    if (s.contains("=")) {
                        final String[] split2 = s.split(Pattern.quote("="));
                        final String key = split2[0];
                        final String val = split2[1];
                        if (key.equals("scratchsessionsid"))
                            ssi = val;
                        else if (key.equals("scratchcsrftoken"))
                            sct = val;
                        else if (key.equals("expires"))
                            e = val;
                    }
                }
            }
        resp.close();

        return new ScratchSession(ssi, sct, e, username);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchLoginException();
    }
}

From source file:com.grouzen.android.serenity.HttpConnection.java

public HttpConnection(String url, HttpConnectionMethod method) {
    this.mMethod = method;
    this.mUrl = url;
    this.mClient = new DefaultHttpClient();
    this.mCookies = new BasicCookieStore();
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;//from   ww w.  j a va2s.c  o  m

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}