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

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

Introduction

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

Prototype

public synchronized final CookieSpecRegistry getCookieSpecs() 

Source Link

Usage

From source file:com.wbtech.ums.NetworkUtil.java

private static void processCookieRejected(DefaultHttpClient client) {
    client.getCookieSpecs().register("esay", new EasyCookieSpecFactory());
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "esay");
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {//from www .j av  a2  s . c  om
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}

From source file:com.soulgalore.crawler.guice.HttpClientProvider.java

/**
 * Get the client./*from   ww w .j  a  v a2 s.  c om*/
 * 
 * @return the client
 */
public HttpClient get() {
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
    cm.setMaxTotal(nrOfThreads);
    cm.setDefaultMaxPerRoute(maxToRoute);
    final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm);

    client.getParams().setParameter("http.socket.timeout", socketTimeout);
    client.getParams().setParameter("http.connection.timeout", connectionTimeout);

    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    CookieSpecFactory csf = new CookieSpecFactory() {
        public CookieSpec newInstance(HttpParams params) {
            return new BestMatchSpecWithURLErrorLog();
        }
    };

    client.getCookieSpecs().register("bestmatchwithurl", csf);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "bestmatchwithurl");

    if (!"".equals(proxy)) {
        StringTokenizer token = new StringTokenizer(proxy, ":");

        if (token.countTokens() == 3) {
            String proxyProtocol = token.nextToken();
            String proxyHost = token.nextToken();
            int proxyPort = Integer.parseInt(token.nextToken());

            HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } else
            System.err.println("Invalid proxy configuration: " + proxy);
    }

    if (auths.size() > 0) {

        for (Auth authObject : auths) {
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(authObject.getScope(), authObject.getPort()),
                    new UsernamePasswordCredentials(authObject.getUserName(), authObject.getPassword()));
        }
    }

    return client;
}

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

private <T> T executeRequest(final HttpRequestBase httpRequest, final HttpClientRequest<T> httpClientRequest)
        throws IOException {
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager,
            setFollowRedirects(params, httpClientRequest));
    httpClient.getCookieSpecs().register(NessCookieSpecFactory.NESS_COOKIE_POLICY, new NessCookieSpecFactory());
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retries, false));

    contributeCookies(httpClient, httpClientRequest);

    contributeParameters(httpClient, httpRequest, httpClientRequest);

    contributeHeaders(httpRequest, httpClientRequest);

    contributeVirtualHost(httpRequest, httpClientRequest);

    contributeAuthentication(httpClient, httpClientRequest);

    try {//from w ww.j  ava 2 s  . c o m
        final HttpContext httpContext = new BasicHttpContext();
        final HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);

        final HttpClientResponseHandler<T> responseHandler = httpClientRequest.getHttpHandler();

        try {
            final HttpClientResponse internalResponse = new InternalResponse(httpRequest, httpResponse);
            HttpClientResponse response = internalResponse;

            if (CollectionUtils.isNotEmpty(httpClientObservers)) {
                LOG.trace("Executing Observers");
                for (HttpClientObserver observer : httpClientObservers) {
                    response = observer.onResponseReceived(response);
                }

                if (response != internalResponse) {
                    LOG.trace("Response was modified by Observers!");
                }
            }

            if (responseHandler != null) {
                LOG.trace("Executing Response Handler");
                return responseHandler.handle(response);
            } else {
                LOG.debug("No response handler found, discarding response.");
                return null;
            }
        } finally {
            // Make sure that the content has definitely been consumed. Otherwise,
            // keep-alive does not work.
            EntityUtils.consume(httpResponse.getEntity());
        }
    } catch (IOException ioe) {
        LOG.debug(ioe, "Aborting Request!");
        httpRequest.abort();
        throw ioe;
    } catch (RuntimeException re) {
        LOG.debug(re, "Aborting Request!");
        httpRequest.abort();
        throw re;
    }
}

From source file:com.akop.bach.parser.LiveParser.java

@Override
protected DefaultHttpClient createHttpClient(Context context) {
    mLastRedirectedUrl = null;/*from   w w  w  .  j av a  2s. co m*/

    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectHandler(new DefaultRedirectHandler() {
        @Override
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            if (uri != null)
                mLastRedirectedUrl = uri.toString();

            return uri;
        }
    });

    client.getCookieSpecs().register("lenient", new CookieSpecFactory() {
        public CookieSpec newInstance(HttpParams params) {
            return new LenientCookieSpec();
        }
    });

    HttpClientParams.setCookiePolicy(client.getParams(), "lenient");

    return client;
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {//from  w  w w  . j a v  a2  s. c om
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:org.apache.solr.client.solrj.impl.Krb5HttpClientConfigurer.java

public void configure(DefaultHttpClient httpClient, SolrParams config) {
    super.configure(httpClient, config);

    if (System.getProperty(LOGIN_CONFIG_PROP) != null) {
        String configValue = System.getProperty(LOGIN_CONFIG_PROP);

        if (configValue != null) {
            logger.info("Setting up SPNego auth with config: " + configValue);
            final String useSubjectCredsProp = "javax.security.auth.useSubjectCredsOnly";
            String useSubjectCredsVal = System.getProperty(useSubjectCredsProp);

            // "javax.security.auth.useSubjectCredsOnly" should be false so that the underlying
            // authentication mechanism can load the credentials from the JAAS configuration.
            if (useSubjectCredsVal == null) {
                System.setProperty(useSubjectCredsProp, "false");
            } else if (!useSubjectCredsVal.toLowerCase(Locale.ROOT).equals("false")) {
                // Don't overwrite the prop value if it's already been written to something else,
                // but log because it is likely the Credentials won't be loaded correctly.
                logger.warn("System Property: " + useSubjectCredsProp + " set to: " + useSubjectCredsVal
                        + " not false.  SPNego authentication may not be successful.");
            }//from  ww w  . j a va2 s  .c o  m

            javax.security.auth.login.Configuration.setConfiguration(jaasConfig);
            //Enable only SPNEGO authentication scheme.
            AuthSchemeRegistry registry = new AuthSchemeRegistry();
            registry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, false));
            httpClient.setAuthSchemes(registry);
            // Get the credentials from the JAAS configuration rather than here
            Credentials useJaasCreds = new Credentials() {
                public String getPassword() {
                    return null;
                }

                public Principal getUserPrincipal() {
                    return null;
                }
            };

            SolrPortAwareCookieSpecFactory cookieFactory = new SolrPortAwareCookieSpecFactory();
            httpClient.getCookieSpecs().register(cookieFactory.POLICY_NAME, cookieFactory);
            httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, cookieFactory.POLICY_NAME);

            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, useJaasCreds);

            httpClient.addRequestInterceptor(bufferedEntityInterceptor);
        } else {
            httpClient.getCredentialsProvider().clear();
        }
    }
}