Example usage for org.apache.http.impl.client DefaultHttpClient setCookieStore

List of usage examples for org.apache.http.impl.client DefaultHttpClient setCookieStore

Introduction

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

Prototype

public synchronized void setCookieStore(final CookieStore cookieStore) 

Source Link

Usage

From source file:org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest.java

public HttpResponse sendConsentGetRequest(DefaultHttpClient client, String locationURL, CookieStore cookieStore,
        List<NameValuePair> consentRequiredClaimsFromResponse) throws Exception {

    HttpClient httpClientWithoutAutoRedirections = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCookieStore(cookieStore).build();
    HttpGet getRequest = new HttpGet(locationURL);
    getRequest.setHeader("User-Agent", OAuth2Constant.USER_AGENT);
    HttpResponse response = httpClientWithoutAutoRedirections.execute(getRequest);

    consentRequiredClaimsFromResponse.addAll(Utils.getConsentRequiredClaimsFromResponse(response));
    Header locationHeader = response.getFirstHeader(OAuth2Constant.HTTP_RESPONSE_HEADER_LOCATION);
    HttpResponse httpResponse = sendGetRequest(httpClientWithoutAutoRedirections, locationHeader.getValue());
    client.setCookieStore(cookieStore);
    EntityUtils.consume(response.getEntity());
    return httpResponse;
}

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

/**
 * Convenience method for sending HTTP requests.
 * <b><span style="color:red">Note</span></b>: This method is intended to be
 * used internally, not by end-users.//from  w  ww.j a  v a  2 s .  c om
 * 
 * @param baseURL - <b>Example</b>: http://minus.com/api
 * @param parametersBody - The parameters (name => value pairs) to pass to
 *            the request.
 * @param sessionId - If <tt>null</tt> or empty, then create and use a new
 *            session, otherwise, use the specified session_id (which is
 *            stored in a cookie).
 * @param requestType
 * @param additionalRequestHeaders -
 * @param expectedResponseType
 * @return The response retrieved from Minus API.
 * @throws MinusException
 */
private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders,
        final ExpectedResponseType expectedResponseType) throws MinusException {

    DefaultHttpClient client = null;
    HttpRequestBase request = null;
    InputStream responseContent = null;
    boolean errorOccured = false;

    try {
        if (requestType == RequestType.GET) {
            request = new HttpGet(baseURL);
            if (parametersBody != null && !parametersBody.isEmpty()) {
                request = appendParametersToRequest(request, parametersBody);
            }

        } else if (requestType == RequestType.POST) {
            UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody),
                    HTTP.UTF_8);
            request = new HttpPost(baseURL);
            ((HttpPost) request).setEntity(encodedEntity);

        } else {
            throw new MinusException("The method (" + requestType + ") is unknown, weird ...");
        }

        request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT));
        if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) {
            for (Header aHeader : additionalRequestHeaders) {
                request.addHeader(aHeader);
            }
        }

        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        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();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // Execute the request ... pass local context as a parameter
        HttpResponse resp = client.execute(request, localContext);

        // 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;
            }
        }

        Object result = null;
        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                if (expectedResponseType == ExpectedResponseType.STRING) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) {
                    result = entity;
                }
            }
        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result, sessionCookie);

    } catch (Exception e) {
        errorOccured = true;
        if (request != null) {
            request.abort();
        }
        String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            // We must not close the client is the expected response is an
            // InputStream. Indeed, if ever we close the client, we won't be
            // able to read the response because of SocketException.
            if (errorOccured) {
                client.getConnectionManager().shutdown();
            } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) {
                client.getConnectionManager().shutdown();
            }
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public String getUrlData(String url) {
    String websiteData = null;/*from   w  w  w . j a v a 2  s .  c  om*/

    if (!this.logged_in) {
        System.out.println("--1--- LOGIN START -----");
        this.logged_in = login();
        System.out.println("--1--- LOGIN END   -----");
    }

    try {
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is
        // established.
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient client = new DefaultHttpClient(httpParameters);
        client.setCookieStore(cookie_jar);
        // Log.d("cookie_jar", "->" + String.valueOf(cookie_jar));

        URI uri = new URI(url);
        HttpGet method = new HttpGet(uri);

        method.addHeader("User-Agent",
                "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10");
        method.addHeader("Pragma", "no-cache");

        HttpResponse res = client.execute(method);
        InputStream data = res.getEntity().getContent();
        websiteData = generateString(data);
        client.getConnectionManager().shutdown();

    } catch (SocketTimeoutException e2) {
        Log.d("HTMLDownloader", "Connectiont timout: " + e2);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (UnknownHostException x) {
        Log.d("HTMLDownloader", ": " + x);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return websiteData;
}

From source file:com.sun.jersey.client.apache4.ApacheHttpClient4.java

/**
 * Create a default Apache HTTP client handler.
 *
 * @param cc ClientConfig instance. Might be null.
 *
 * @return a default Apache HTTP client handler.
 *///from   www. j  a v a 2s.  co m
private static ApacheHttpClient4Handler createDefaultClientHandler(final ClientConfig cc) {

    Object connectionManager = null;
    Object httpParams = null;

    if (cc != null) {
        connectionManager = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER);
        if (connectionManager != null) {
            if (!(connectionManager instanceof ClientConnectionManager)) {
                Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING,
                        "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER
                                + " (" + connectionManager.getClass().getName()
                                + ") - not instance of org.apache.http.conn.ClientConnectionManager.");
                connectionManager = null;
            }
        }

        httpParams = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS);
        if (httpParams != null) {
            if (!(httpParams instanceof HttpParams)) {
                Logger.getLogger(ApacheHttpClient4.class.getName()).log(Level.WARNING,
                        "Ignoring value of property " + ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS + " ("
                                + httpParams.getClass().getName()
                                + ") - not instance of org.apache.http.params.HttpParams.");
                httpParams = null;
            }
        }
    }

    final DefaultHttpClient client = new DefaultHttpClient((ClientConnectionManager) connectionManager,
            (HttpParams) httpParams);

    CookieStore cookieStore = null;
    boolean preemptiveBasicAuth = false;

    if (cc != null) {
        for (Map.Entry<String, Object> entry : cc.getProperties().entrySet())
            client.getParams().setParameter(entry.getKey(), entry.getValue());

        if (cc.getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES))
            client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);

        Object credentialsProvider = cc.getProperty(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER);
        if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) {
            client.setCredentialsProvider((CredentialsProvider) credentialsProvider);
        }

        final Object proxyUri = cc.getProperties().get(ApacheHttpClient4Config.PROPERTY_PROXY_URI);
        if (proxyUri != null) {
            final URI u = getProxyUri(proxyUri);
            final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme());

            if (cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME)
                    && cc.getProperties().containsKey(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD)) {

                client.getCredentialsProvider().setCredentials(new AuthScope(u.getHost(), u.getPort()),
                        new UsernamePasswordCredentials(
                                cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_USERNAME).toString(),
                                cc.getProperty(ApacheHttpClient4Config.PROPERTY_PROXY_PASSWORD).toString()));

            }
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }

        preemptiveBasicAuth = cc
                .getPropertyAsFeature(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION);
    }

    if (client.getParams().getParameter(ClientPNames.COOKIE_POLICY) == null || !client.getParams()
            .getParameter(ClientPNames.COOKIE_POLICY).equals(CookiePolicy.IGNORE_COOKIES)) {
        cookieStore = new BasicCookieStore();
        client.setCookieStore(cookieStore);
    }

    return new ApacheHttpClient4Handler(client, cookieStore, preemptiveBasicAuth);
}

From source file:com.ibm.sbt.services.client.ClientService.java

/**
 * Initialize the associated Endpoint with the specified HttpClient.
 * //w  ww. j a va 2  s  .  c o m
 * @param httpClient
 * @throws ClientServicesException
 */
protected void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
    if (endpoint != null) {
        CookieStore cookies = endpoint.getCookies();
        httpClient.setCookieStore(cookies);
        endpoint.initialize(httpClient);
    }
}

From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java

public String get_reader_stream(String url, List<NameValuePair> values, ByteArrayOutputStream data,
        Boolean need_login) {/*from   ww  w .  ja v  a  2  s .  co m*/

    if ((need_login) && (!this.logged_in)) {
        System.out.println("--2--- LOGIN START -----");
        this.logged_in = login();
        System.out.println("--2--- LOGIN END   -----");
    }

    if ((values == null) && (data == null)) {
        return null;
    } else if (data == null) {
        String websiteData = null;
        URI uri = null;
        DefaultHttpClient client = new DefaultHttpClient();

        // insert cookies from cookie_jar
        client.setCookieStore(cookie_jar);

        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return null;
        }

        HttpPost method = new HttpPost(uri);
        method.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
        method.addHeader("Pragma", "no-cache");
        method.addHeader("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(values, HTTP.UTF_8);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        method.addHeader(entity.getContentType());
        method.setEntity(entity);

        try {
            HttpResponse res2 = client.execute(method);
            // System.out.println("login response ->" +
            // String.valueOf(res2.getStatusLine()));
            InputStream data2 = res2.getEntity().getContent();
            websiteData = generateString(data2);

        } catch (ClientProtocolException e) {
            // e.printStackTrace();
            return null;
        } catch (IOException e) {
            // e.printStackTrace();
            return null;
        }

        client.getConnectionManager().shutdown();

        return websiteData;

    } else {
        try {
            // url Header textdata
            InputStream i = this.doPost2(url, values, data);
            return this.convertStreamToString(i);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeCookies(final DefaultHttpClient httpClient,
        final HttpClientRequest<T> httpClientRequest) {
    final List<Cookie> cookies = httpClientRequest.getCookies();

    if (CollectionUtils.isNotEmpty(cookies)) {
        final CookieStore cookieStore = new BasicCookieStore();
        for (final Cookie cookie : cookies) {
            final BasicClientCookie httpCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());

            final int maxAge = cookie.getMaxAge();

            if (maxAge > 0) {
                final Date expire = new Date(System.currentTimeMillis() + maxAge * 1000L);
                httpCookie.setExpiryDate(expire);
                httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(maxAge));
            }/*from   w  ww  .  j  a v  a  2 s  .c o m*/

            httpCookie.setVersion(1);
            httpCookie.setPath(cookie.getPath());
            httpCookie.setDomain(cookie.getDomain());
            httpCookie.setSecure(cookie.getSecure());

            LOG.debug("Adding cookie to the request: '%s'", httpCookie);
            cookieStore.addCookie(httpCookie);
        }
        httpClient.setCookieStore(cookieStore);
    } else {
        LOG.debug("No cookies found.");
        httpClient.setCookieStore(null);
    }
}

From source file:com.enjoy.nerd.http.AsyncHttpClient.java

/**
 * Puts a new request in queue as a new thread in pool to be executed
 *
 * @param client          HttpClient to be used for request, can differ in single requests
 * @param contentType     MIME body type, for POST and PUT requests, may be null
 * @param context         Context of Android application, to hold the reference of request
 * @param httpContext     HttpContext in which the request will be executed
 * @param responseHandler ResponseHandler or its subclass to put the response into
 * @param uriRequest      instance of HttpUriRequest, which means it must be of HttpDelete,
 *                        HttpPost, HttpGet, HttpPut, etc.
 * @return RequestHandle of future request process
 *//*from w  ww  . ja  v a 2 s.c om*/
protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext,
        HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler,
        Context context) {
    if (contentType != null) {
        uriRequest.setHeader("Content-Type", contentType);
    }

    responseHandler.setRequestHeaders(uriRequest.getAllHeaders());
    responseHandler.setRequestURI(uriRequest.getURI());

    //tangwh  add, ?????cookie?cookie?setCookieStore?uriRequestHeader?
    //??http2Cookie???cookieStore
    client.setCookieStore(null);

    Future<?> request = threadPool
            .submit(new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler));

    if (context != null) {
        // Add request to request map
        List<WeakReference<Future<?>>> requestList = requestMap.get(context);
        if (requestList == null) {
            requestList = new LinkedList<WeakReference<Future<?>>>();
            requestMap.put(context, requestList);
        }

        requestList.add(new WeakReference<Future<?>>(request));

        // TODO: Remove dead weakrefs from requestLists?
    }

    return new RequestHandle(request);
}

From source file:com.mobilyzer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *///www  .j a va 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) {
        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.google.wireless.speed.speedometer.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *//*  www  . jav a 2  s . 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;
}