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

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

Introduction

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

Prototype

void addCookie(Cookie cookie);

Source Link

Document

Adds an Cookie , replacing any existing equivalent cookies.

Usage

From source file:de.chaosfisch.google.youtube.upload.metadata.AbstractMetadataService.java

@Override
public void activateBrowserfeatures(final Upload upload) throws UnirestException {

    // Create a local instance of cookie store
    // Populate cookies if needed
    final CookieStore cookieStore = new BasicCookieStore();
    for (final PersistentCookieStore.SerializableCookie serializableCookie : upload.getAccount()
            .getSerializeableCookies()) {
        final BasicClientCookie cookie = new BasicClientCookie(serializableCookie.getCookie().getName(),
                serializableCookie.getCookie().getValue());
        cookie.setDomain(serializableCookie.getCookie().getDomain());
        cookieStore.addCookie(cookie);
    }//from  w  w w. jav  a 2 s  . c o m

    final HttpClient client = HttpClientBuilder.create().useSystemProperties()
            .setDefaultCookieStore(cookieStore).build();
    Unirest.setHttpClient(client);

    final HttpResponse<String> response = Unirest.get(String.format(VIDEO_EDIT_URL, upload.getVideoid()))
            .asString();

    changeMetadata(response.getBody(), upload);

    final RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(600000).setSocketTimeout(600000)
            .build();
    Unirest.setHttpClient(HttpClientBuilder.create().setDefaultRequestConfig(clientConfig).build());
}

From source file:io.mandrel.requests.http.ApacheHttpRequester.java

public HttpContext prepareContext(Spider spider) {
    CookieStore store = new BasicCookieStore();
    if (cookies() != null)
        cookies().forEach(cookie -> {
            BasicClientCookie theCookie = new BasicClientCookie(cookie.name(), cookie.value());
            theCookie.setDomain(cookie.domain());
            theCookie.setPath(cookie.path());
            theCookie.setExpiryDate(new Date(cookie.expires()));
            theCookie.setSecure(cookie.secure());
            store.addCookie(theCookie);
        });//from www.ja  va 2  s .  co  m

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, store);
    return localContext;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * CookieStore per AccountName to prevent mixing of the sessions.
 * /*from w  w w  .  j  av  a  2  s.  c o m*/
 * @param accountName
 *            accountName or null (default)
 * @return
 */
private static HttpContext createHttpContext(String accountName, String authtoken) {
    BasicHttpContext ctx = new BasicHttpContext();
    CookieStore store;
    synchronized (CL_LOCK) {
        store = COOKIES.get(accountName);
        if (store == null) {
            store = new BasicCookieStore();
            COOKIES.put(accountName, store);
        }
    }
    ctx.setAttribute(ClientContext.COOKIE_STORE, store);

    if (authtoken != null) {
        boolean add = true;
        for (Cookie cookie : store.getCookies()) {
            if (COOKIE_SESSION_NAME.equals(cookie.getName())) {
                if (authtoken.equals(cookie.getValue())) {
                    add = false;
                }
                break;
            }
        }
        if (add) {
            BasicClientCookie sessionCookie = new BasicClientCookie(COOKIE_SESSION_NAME, authtoken);
            sessionCookie.setSecure(true);
            store.addCookie(sessionCookie);
        }
    }

    return ctx;
}

From source file:fr.cnes.sitools.metacatalogue.resources.proxyservices.RedirectorHttps.java

/**
 * CloseableHttpResponse/*from   w ww.jav a  2 s . c  o m*/
 * 
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public CloseableHttpResponse getCloseableResponse(String url, Series<Cookie> cookies)
        throws ClientProtocolException, IOException {

    HttpClientBuilder httpclientBuilder = HttpClients.custom();

    if (withproxy) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                ProxySettings.getProxyUser(), ProxySettings.getProxyPassword()));
        httpclientBuilder.setDefaultCredentialsProvider(credsProvider).build();
    }
    CloseableHttpClient httpclient = httpclientBuilder.build();

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

    Iterator<Cookie> iter = cookies.iterator();

    while (iter.hasNext()) {
        Cookie restCookie = iter.next();
        BasicClientCookie cookie = new BasicClientCookie(restCookie.getName(), restCookie.getValue());
        // cookie.setDomain(restCookie.getDomain());
        cookie.setDomain(getDomainName(url));
        cookie.setPath(restCookie.getPath());
        cookie.setSecure(true);
        // cookie.setExpiryDate(restCookie);
        cookieStore.addCookie(cookie);
    }

    context.setCookieStore(cookieStore);

    HttpGet httpget = new HttpGet(url);

    Builder configBuilder = RequestConfig.custom();

    if (withproxy) {
        HttpHost proxy = new HttpHost(ProxySettings.getProxyHost(),
                Integer.parseInt(ProxySettings.getProxyPort()), "http");
        configBuilder.setProxy(proxy).build();
    }

    RequestConfig config = configBuilder.build();
    httpget.setConfig(config);

    return httpclient.execute(httpget, context);

}

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

@NotWorking
public void toggleCommentsEnabled() throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.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);/* www  . j  a v a 2s . c o m*/
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

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

    final HttpUriRequest update = RequestBuilder.put()
            .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID()
                    + "/toggle-comments/")
            .addHeader("Accept", "*/*")
            .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/")
            .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")
            .addHeader("Cookie",
                    "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                            + this.session.getCSRFToken())
            .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();
    try {
        resp = httpClient.execute(update);
        System.out.println("current status:" + resp.getStatusLine().getStatusCode());
        if (resp.getStatusLine().getStatusCode() != 200)
            throw new ScratchProjectException();
        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);

        System.out.println(result);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
}

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 v  a 2 s  .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:edu.mit.scratch.ScratchSession.java

public ScratchCloudSession getCloudSession(final int projectID) throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    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);/*from  w ww  .j  a  va2 s . c  o  m*/
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

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

    final HttpUriRequest project = RequestBuilder.get()
            .setUri("https://scratch.mit.edu/projects/" + projectID + "/").addHeader("Accept", "text/html")
            .addHeader("Referer", "https://scratch.mit.edu").build();
    try {
        resp = httpClient.execute(project);
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
    String projectStr = null;
    try {
        projectStr = Scratch.consume(resp);
    } catch (IllegalStateException | IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }
    final Pattern p = Pattern.compile("cloudToken: '([a-zA-Z0-9\\-]+)'");
    final Matcher m = p.matcher(projectStr);
    m.find();
    final String cloudToken = m.group(1);

    return new ScratchCloudSession(this, cloudToken, projectID);
}

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

public int getMessageCount() throws ScratchUserException {
    try {//from   w  w  w .  ja  va  2s. 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.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(debug);

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

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://api.scratch.mit.edu/users/" + this.getUsername() + "/messages/count")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .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 ScratchUserException();
        }

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

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        final JSONObject jsonOBJ2 = new JSONObject(result.toString().trim());

        return jsonOBJ2.getInt("count");
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}

From source file:ti.modules.titanium.network.NetworkModule.java

/**
 * Removes all the cookies with the domain matched with the given value.
 * @param domain the domain of the cookie to remove. It is case-insensitive.
 *//* w  w  w .  ja va2s  .  co m*/
@Kroll.method
public void removeHTTPCookiesForDomain(String domain) {
    CookieStore cookieStore = getHTTPCookieStoreInstance();
    List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    cookieStore.clear();
    for (Cookie cookie : cookies) {
        String cookieDomain = cookie.getDomain();
        if (!(domainMatch(cookieDomain, domain))) {
            cookieStore.addCookie(cookie);
        }
    }
}

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

public ScratchUser update() throws ScratchUserException {
    try {//from  w  w  w.j  a v  a2  s. co  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");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(debug);

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

        final HttpUriRequest update = RequestBuilder.get().setUri("https://api.scratch.mit.edu/users/arinerron")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/arinerron")
                .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 ScratchUserException();
        }

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

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("msgdata:" + result.toString()); // remove later!
        final JSONObject jsonObject = new JSONObject(result.toString().trim());

        this.join_date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
                .parse(jsonObject.getJSONObject("history").getString("joined"));
        final JSONObject profile = jsonObject.getJSONObject("profile");
        this.user_id = profile.getInt("id");
        this.status = profile.getString("status");
        this.bio = profile.getString("bio");
        this.country = profile.getString("country");
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final JSONException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final ParseException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }

    return this;
}