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.num.mobiperf.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///ww w.ja  v a  2s .co 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) {
        // 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.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}.//from w  ww.j  a v  a  2  s.c  o  m
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.mobicents.applications.ussd.examples.http.push.HTTPPush.java

protected void establishSession() {
    this.context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    this.context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:com.osbitools.ws.shared.web.BasicWebUtils.java

public WebResponse uploadFile(String path, String fname, InputStream in, String stoken)
        throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(path);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    StringBody fn = new StringBody(fname, ContentType.MULTIPART_FORM_DATA);

    builder.addPart("fname", fn);
    builder.addBinaryBody("file", in, ContentType.APPLICATION_XML, fname);

    BasicCookieStore cookieStore = new BasicCookieStore();

    if (stoken != null) {
        BasicClientCookie cookie = new BasicClientCookie(Constants.SECURE_TOKEN_NAME, stoken);
        cookie.setDomain(TestConstants.JETTY_HOST);
        cookie.setPath("/");
        cookieStore.addCookie(cookie);//  ww  w .j  ava  2 s.  c o m
    }

    TestConstants.LOG.debug("stoken=" + stoken);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
    HttpEntity entity = builder.build();

    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    String body;
    ResponseHandler<String> handler = new BasicResponseHandler();
    try {
        body = handler.handleResponse(response);
    } catch (HttpResponseException e) {
        return new WebResponse(e.getStatusCode(), e.getMessage());
    }

    return new WebResponse(response.getStatusLine().getStatusCode(), body);
}

From source file:org.keycloak.testsuite.oauth.OAuthRedirectUriTest.java

@Test
public void testWithCustomScheme() throws IOException {
    oauth.clientId("custom-scheme");

    oauth.redirectUri(/*from www  . jav a2  s .  co m*/
            "android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login");
    oauth.openLoginForm();

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    String loginUrl = driver.getCurrentUrl();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setDefaultCookieStore(cookieStore).build();

    try {
        String loginPage = SimpleHttp.doGet(loginUrl, client).asString();

        String formAction = loginPage.split("action=\"")[1].split("\"")[0].replaceAll("&amp;", "&");
        SimpleHttp.Response response = SimpleHttp.doPost(formAction, client)
                .param("username", "test-user@localhost").param("password", "password").asResponse();

        response.getStatus();
        assertThat(response.getFirstHeader("Location"), Matchers.startsWith(
                "android-app://org.keycloak.examples.cordova/https/keycloak-cordova-example.github.io/login"));
    } finally {
        client.close();
    }
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * //from w w  w . j av a 2 s  . c  om
 * @param baseURL
 * @param parametersBody
 * @param sessionId
 * @param fileToUpload - The file to upload.
 * @param filename - The name of the file to use during the upload process.
 * @return The response received from the Minus API.
 * @throws MinusException
 */
public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final File fileToUpload, final String filename) throws MinusException {

    DefaultHttpClient client = null;
    HttpPost uploadRequest = null;
    InputStream responseContent = null;

    try {
        String url = baseURL;
        if (parametersBody != null && !parametersBody.isEmpty()) {
            url += CommonUtils.encodeParams(parametersBody);
        }
        uploadRequest = new HttpPost(url);
        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream");
        uploadRequest.setEntity(fileEntity);

        // We add this headers as specified by the Minus.com API during file
        // upload.
        uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin");
        uploadRequest.addHeader("Content-Type", "application/octet-stream");

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

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

        HttpResponse httpResponse = client.execute(uploadRequest);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        StringBuilder result = new StringBuilder();
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity respEntity = httpResponse.getEntity();
            if (respEntity != null) {
                result.append(EntityUtils.toString(respEntity));
                EntityUtils.consume(respEntity);
            }

        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine());
            if (uploadRequest != null) {
                errMsg.append(" : ").append(uploadRequest.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result.toString(), sessionCookie);

    } catch (Exception e) {
        if (uploadRequest != null) {
            uploadRequest.abort();
        }
        String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:ilarkesto.net.ApacheHttpDownloader.java

public HttpContext getContext() {
    if (context == null) {
        context = new BasicHttpContext();
        context.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
    }/* w  w  w  . j  a  v a  2s  . co m*/
    return context;
}

From source file:org.callimachusproject.client.HttpClientFactoryTest.java

@Test
public void testCookieStored() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    do {/*from   www  .  j av a2s  .  co  m*/
        HttpGet get = new HttpGet("http://example.com/setcookie");
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        BasicHttpResponse setcookie = new BasicHttpResponse(_200);
        setcookie.addHeader("Set-Cookie", "oat=meal");
        setcookie.addHeader("Cache-Control", "no-store");
        responses.add(setcookie);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                assertTrue(response.containsHeader("Set-Cookie"));
                return null;
            }
        }, localContext);
    } while (false);
    do {
        HttpGet get = new HttpGet("http://example.com/getcookie");
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        BasicHttpResponse getcookie = new BasicHttpResponse(_200);
        responses.add(getcookie);
        client.execute(get, new ResponseHandler<Void>() {
            public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                assertEquals(_200.getStatusCode(), response.getStatusLine().getStatusCode());
                assertContains("oat=meal", asString(response.getEntity()));
                return null;
            }
        }, localContext);
    } while (false);
}

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

/**
 * Return an appropriately-configured HTTP client.
 *//*from  w w  w  .  j ava  2s . co 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:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClient.java

/**
 *  It creates an {@link HttpContext} object with a cookie store that will contain the cookies returned by the user in the {@link CloseableHttpResponse} that is received as parameter.
 *///from w w  w.j a  v a  2 s.  c o m
protected HttpContext createHttpContextWithCookies(CloseableHttpResponse loginResponse) {
    CookieStore cookieStore = new BasicCookieStore();
    createAndAddCookiesOnStoreForHeaders(cookieStore, loginResponse.getAllHeaders());
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    return httpContext;
}