Example usage for org.apache.http.client.params CookiePolicy BEST_MATCH

List of usage examples for org.apache.http.client.params CookiePolicy BEST_MATCH

Introduction

In this page you can find the example usage for org.apache.http.client.params CookiePolicy BEST_MATCH.

Prototype

String BEST_MATCH

To view the source code for org.apache.http.client.params CookiePolicy BEST_MATCH.

Click Source Link

Document

The default 'best match' policy.

Usage

From source file:com.gypsai.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httppostclient = new DefaultHttpClient();
    httppostclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    try {//from  w w w. ja  va 2 s . c om

        String loginUrl = "http://www.cnsfk.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes";
        //String loginUrl = "http://renren.com/PLogin.do";

        String testurl = "http://www.baidu.com";
        HttpGet httpget = new HttpGet(testurl);

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        //System.out.println(istostring(entity.getContent()));

        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                //     System.out.println("- " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost(loginUrl);

        String password = MD5.MD5Encode("luom1ng");
        String redirectURL = "http://www.renren.com/home";
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "gypsai@foxmail.com"));
        nvps.add(new BasicNameValuePair("password", password));
        // nvps.add(new BasicNameValuePair("origURL", redirectURL));  
        // nvps.add(new BasicNameValuePair("domain", "renren.com"));  
        //  nvps.add(new BasicNameValuePair("autoLogin", "true"));  
        //  nvps.add(new BasicNameValuePair("formName", ""));  
        //  nvps.add(new BasicNameValuePair("method", ""));  
        //  nvps.add(new BasicNameValuePair("submit", ""));  

        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        httpost.setHeader("User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.28 (KHTML, like Gecko) Chrome/26.0.1397.2 Safari/537.28");

        //posthttpclient
        //DefaultHttpClient httppostclient = new DefaultHttpClient();

        //postheader
        Header[] pm = httpost.getAllHeaders();
        for (Header header : pm) {
            System.out.println("%%%%->" + header.toString());
        }

        //
        response = httppostclient.execute(httpost);

        EntityUtils.consume(response.getEntity());

        doget();
        //
        //

        //httppostclient.getConnectionManager().shutdown();

        //cookie
        List<Cookie> cncookies = httppostclient.getCookieStore().getCookies();
        System.out.println("Post logon cookies:");

        if (cncookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cncookies.size(); i++) {
                System.out.println("- " + cncookies.get(i).getName().toString() + "   ---->"
                        + cncookies.get(i).getValue().toString());
            }
        }

        //
        submit();

        //httpheader
        entity = response.getEntity();
        Header[] m = response.getAllHeaders();
        for (Header header : m) {
            //System.out.println("+++->"+header.toString());
        }
        //System.out.println(response.getAllHeaders());
        System.out.println(entity.getContentEncoding());

        //statusline
        System.out.println("Login form get: " + response.getStatusLine());

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        //  httpclient.getConnectionManager().shutdown();
        //httppostclient.getConnectionManager().shutdown();
    }
}

From source file:dk.i2m.drupal.DrupalHttpClient.java

public DrupalHttpClient() {
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, 30000)
            .setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH)
            .setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8)
            .setParameter(AllClientPNames.SO_TIMEOUT, 30000);

    this.setParams(params);
}

From source file:dk.i2m.drupal.DrupalHttpClient.java

DrupalHttpClient(int connectionTimeout, int socketTimeout) {
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout)
            .setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH)
            .setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8)
            .setParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);

    this.setParams(params);
}

From source file:gmusic.api.comm.ApacheConnector.java

public ApacheConnector() {
    HttpParams params = new BasicHttpParams();
    params.removeParameter("User-Agent");
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    // HttpConnectionParams.setConnectionTimeout(params, 150000);
    // HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:gmusic.api.api.comm.ApacheConnector.java

public ApacheConnector() {
    final HttpParams params = new BasicHttpParams();
    params.removeParameter("User-Agent");
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    // HttpConnectionParams.setConnectionTimeout(params, 150000);
    // HttpConnectionParams.setSoTimeout(params, socketTimeoutMillis);
    httpClient = new DefaultHttpClient(params);
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}

From source file:com.sangupta.jerry.http.WebInvoker.java

/**
 * Return the HTTP response body for a GET request to the given URL. In case
 * an {@link IOException} is thrown, it will be eaten up, logged at DEBUG
 * level, and <code>null</code> returned.
 * /*from  w w w .j  a v a2  s.c o m*/
 * @param url
 *            the url to hit
 *            
 * @return the string response body
 */
public static String fetchResponse(String url) {
    return fetchResponse(url, CookiePolicy.BEST_MATCH);
}

From source file:com.sangupta.jerry.http.WebInvoker.java

/**
 * Return the {@link WebResponse} for a GET request to the given URL using
 * the {@link CookiePolicy#BEST_MATCH} cookie policy . In case an
 * {@link IOException} is thrown, it will be eaten up, logged at DEBUG
 * level, and <code>null</code> returned.
 * /*from  w w w  .j  a  va  2s.c  om*/
 * @param url
 *            the url to hit
 *            
 * @return the {@link WebResponse} obtained
 */
public static WebResponse getResponse(String url) {
    return getResponse(url, CookiePolicy.BEST_MATCH);
}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;//from  w  w w .j av  a2  s  . c  om

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java

public static void configureClient(AbstractHttpClient client, String userAgent) {
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BEST_MATCH);

    if (userAgent != null) {
        HttpProtocolParams.setUserAgent(client.getParams(), userAgent);
    }/*from w  ww  .  j av  a  2 s.c  o  m*/
    HttpProtocolParams.setUseExpectContinue(client.getParams(), true);
    client.getParams().setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    HttpConnectionParams.setConnectionTimeout(client.getParams(), CONNNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(client.getParams(), SOCKET_TIMEOUT);

    //AuthParams.setCredentialCharset(client.getParams(), "UTF-8");
}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }/*from   w w w  .  j  a v a2  s .c  o  m*/

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}