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:com.hp.mqm.clt.RestClient.java

protected CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
    //doFirstLogin();
    if (LWSSO_TOKEN == null) {
        login();//from   w  ww  . j  a  v a  2 s.c o m
    }
    HttpContext localContext = new BasicHttpContext();
    CookieStore localCookies = new BasicCookieStore();
    localCookies.addCookie(LWSSO_TOKEN);
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
    addClientTypeHeader(request);
    CloseableHttpResponse response = httpClient.execute(request, localContext);
    if (isLoginNecessary(response)) { // if request fails with 401 do login and execute request again
        HttpClientUtils.closeQuietly(response);
        login();
        localCookies.clear();
        localCookies.addCookie(LWSSO_TOKEN);
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, localCookies);
        response = httpClient.execute(request, localContext);
    }
    return response;
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

@Override
@Asynchronous//from   w w w . j  a v a2  s .  co m
public void importFile() {
    try {

        String urlString = "http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_lotfac.zip";

        DefaultHttpClient client = new DefaultHttpClient();
        CookieStore cookieStore = client.getCookieStore();

        BasicClientCookie cookie = new BasicClientCookie("abc", "123");
        cookie.setDomain("xyz.net");
        cookie.setPath("/");

        cookieStore.addCookie(cookie);
        client.setCookieStore(cookieStore);

        HttpGet request = new HttpGet(urlString);

        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            long len = entity.getContentLength();

            storeFile(entity.getContent());
        }
        System.out.println("### FINISHED ###");
    } catch (IOException ex) {
        logger.error(ex);
    }

}

From source file:com.lidroid.xutils.HttpUtils.java

public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url, RequestParams params,
        RequestCallBack<T> callBack) {
    if (url == null)
        throw new IllegalArgumentException("url may not be null");

    HttpRequest request = new HttpRequest(method, url);

    // headercookie
    String cookieStore = J_NetManager.VolleyCookie;
    if (url.contains("func=do_register_all")) {
        CookieStore cs = httpClient.getCookieStore();
        cs.addCookie(new BasicClientCookie2("cookie", cookieStore));
    } else {/*from  w w  w .ja v a2 s  . co m*/
        request.setHeader("Cookie", cookieStore);
    }

    return sendRequest(request, params, callBack);
}

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

public void clearMessages() throws ScratchUserException {
    try {/*from www  . ja  va 2  s.  co  m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).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();
        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/messages/ajax/messages-clear/")
                .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")
                .addHeader("Cookie",
                        "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                                + this.session.getCSRFToken())
                .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();

        httpClient.execute(update);
    } catch (final Exception e) {
        throw new ScratchUserException();
    }
}

From source file:com.mobilyzer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 */// www .jav  a  2  s.  c  om
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Logger.w("Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

From source file:com.subgraph.vega.impl.scanner.Scanner.java

@Override
public synchronized void startScanner(IScannerConfig config) {
    synchronized (lock) {
        if (!isLocked) {
            throw new IllegalStateException("Scanner must be locked before starting scan.");
        }/*from   w w w. java  2s .  c  om*/
    }

    if (currentScan != null && currentScan.getScanStatus() != IScanInstance.SCAN_COMPLETED
            && currentScan.getScanStatus() != IScanInstance.SCAN_CANCELLED) {
        throw new IllegalStateException(
                "Scanner is already running.  Verify scanner is not running with getScannerStatus() before trying to start.");
    }

    if (config.getBaseURI() == null)
        throw new IllegalArgumentException("Cannot start scan because no baseURI was specified");

    IHttpRequestEngineConfig requestEngineConfig = requestEngineFactory.createConfig();
    if (config.getCookieList() != null) {
        CookieStore cookieStore = requestEngineConfig.getCookieStore();
        for (Cookie c : config.getCookieList()) {
            cookieStore.addCookie(c);
        }
    }

    if (config.getMaxRequestsPerSecond() > 0) {
        requestEngineConfig.setRequestsPerMinute(config.getMaxRequestsPerSecond() * 60);
    }

    requestEngineConfig.setMaxConnections(config.getMaxConnections());
    requestEngineConfig.setMaxConnectionsPerRoute(config.getMaxConnections());
    requestEngineConfig.setMaximumResponseKilobytes(config.getMaxResponseKilobytes());
    final HttpClient client = requestEngineFactory.createUnencodingClient();
    final IHttpRequestEngine requestEngine = requestEngineFactory.createRequestEngine(client,
            requestEngineConfig);
    reloadModules();
    resetModuleTimestamps();
    currentWorkspace.lock();

    currentScan = currentWorkspace.getScanAlertRepository().createNewScanInstance();
    scannerTask = new ScannerTask(currentScan, this, config, requestEngine, currentWorkspace,
            contentAnalyzerFactory.createContentAnalyzer(currentScan), responseProcessingModules, basicModules);
    scannerThread = new Thread(scannerTask);
    currentWorkspace.getScanAlertRepository().setActiveScanInstance(currentScan);
    currentScan.updateScanStatus(IScanInstance.SCAN_STARTING);
    scannerThread.start();
}

From source file:com.google.wireless.speed.speedometer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *//* ww  w  .  jav  a  2 s.c o m*/
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        Log.w(SpeedometerApp.TAG, "Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}

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

private void addProxyCookie(CookieStore cookieStore) {
    BasicClientCookie proxyCookie = new BasicClientCookie(
            properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE_NAME),
            properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE_VALUE));
    proxyCookie.setDomain(properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE_DOMAIN));
    proxyCookie.setPath("/");
    cookieStore.addCookie(proxyCookie);
}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Set a cookie, all previous cookies will be cleared.
 * //from  w  ww . j ava2  s .co  m
 * @param name
 *            the cookie name
 * @param value
 *            its value
 */
public void setCookie(String name, String value) {
    CookieStore store = mClient.getCookieStore();
    store.clear();
    BasicClientCookie cookie = new BasicClientCookie(name, value);
    cookie.setDomain(mHostName);
    store.addCookie(cookie);
}

From source file:cl.nic.dte.net.ConexionSii.java

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII,
        String token, String urlEnvio, String hostEnvio)
        throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(urlEnvio);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2)));
    reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length())));
    reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2)));
    reqEntity.addPart("dvCompany",
            new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length())));

    FileBody bin = new FileBody(archivoEnviarSII);
    reqEntity.addPart("archivo", bin);

    httppost.setEntity(reqEntity);//  ww w . j a  v a2s . co  m

    BasicClientCookie cookie = new BasicClientCookie("TOKEN", token);
    cookie.setPath("/");
    cookie.setDomain(hostEnvio);
    cookie.setSecure(true);
    cookie.setVersion(1);

    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);

    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));

    HttpResponse response = httpclient.execute(httppost, localContext);

    HttpEntity resEntity = response.getEntity();

    RECEPCIONDTEDocument resp = null;

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();
    opts.setLoadSubstituteNamespaces(namespaces);

    resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts);

    return resp;
}