Example usage for org.apache.http.client.params ClientPNames COOKIE_POLICY

List of usage examples for org.apache.http.client.params ClientPNames COOKIE_POLICY

Introduction

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

Prototype

String COOKIE_POLICY

To view the source code for org.apache.http.client.params ClientPNames COOKIE_POLICY.

Click Source Link

Document

Defines the name of the cookie specification to be used for HTTP state management.

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 . j av a2 s.c  o m

        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:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from ww  w.j  a v a 2 s.  co m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));

        HttpHost targetHost = new HttpHost("pt.3g.qq.com");
        HttpHost proxy = new HttpHost("133.13.162.149", 8080);

        BasicClientCookie netscapeCookie = null;

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        // httpclient.getCookieStore().addCookie(netscapeCookie);
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        HttpGet httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");

        System.out.println("executing request: " + httpget.getRequestLine());
        System.out.println("via proxy: " + proxy);
        System.out.println("to target: " + targetHost);

        HttpResponse response = httpclient.execute(targetHost, httpget);

        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        InputStream is = entity.getContent();
        StringBuffer sb = new StringBuffer(200);
        byte data[] = new byte[65536];
        int n = 1;
        do {
            n = is.read(data);
            if (n > 0) {
                sb.append(new String(data));
            }
        } while (n > 0);

        // System.out.println(sb);
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");
        Header[] headerlist = response.getAllHeaders();
        for (int i = 0; i < headerlist.length; i++) {
            Header header = headerlist[i];
            if (header.getName().equals("Set-Cookie")) {
                String setCookie = header.getValue();
                String cookies[] = setCookie.split(";");
                for (int j = 0; j < cookies.length; j++) {
                    String cookie[] = cookies[j].split("=");
                    CookieManager.cookie.put(cookie[0], cookie[1]);
                }
            }
            System.out.println(header.getName() + ":" + header.getValue());
        }
        String sid = getSid(sb.toString(), "&");
        System.out.println("sid: " + sid);

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("133.13.162.149", 8080),
                new UsernamePasswordCredentials("43668069", "wf^O^2013"));
        String url = Constant.openUrl + "&" + sid;
        targetHost = new HttpHost(url);

        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        httpget = new HttpGet("/");
        httpget.addHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        Iterator it = CookieManager.cookie.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            netscapeCookie = new BasicClientCookie((String) (key), (String) (value));
            netscapeCookie.setVersion(0);
            netscapeCookie.setDomain(".qq.com");
            netscapeCookie.setPath("/");
            // httpclient.getCookieStore().addCookie(netscapeCookie);
        }

        response = httpclient.execute(targetHost, httpget);

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

From source file:com.jayway.restassured.config.HttpClientConfigTest.java

@Test
public void cookiePolicyIsSetToIgnoreCookiesByDefault() throws Exception {
    final HttpClientConfig httpClientConfig = new HttpClientConfig();

    assertThat((Map<String, String>) httpClientConfig.params(),
            hasEntry(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES));
}

From source file:com.blacklocus.sample.time.HttpClientFactory.java

/**
 * Construct a new HttpClient which uses the {@link #POOL_MGR default connection pool}.
 *
 * @param connectionTimeout highly sensitive to application so must be specified
 * @param socketTimeout highly sensitive to application so must be specified
 *//*  w  w w  .j a v  a2s. c  om*/
public static HttpClient createHttpClient(final int connectionTimeout, final int socketTimeout) {
    return new DefaultHttpClient(POOL_MGR) {
        {
            HttpParams httpParams = getParams();

            // prevent seg fault JVM bug, see https://code.google.com/p/crawler4j/issues/detail?id=136
            httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

            HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
            HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
            HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);

        }
    };
}

From source file:io.restassured.config.HttpClientConfigTest.java

@Test
public void cookiePolicyIsSetToIgnoreCookiesByDefault() throws Exception {
    final HttpClientConfig httpClientConfig = new HttpClientConfig();

    assertThat(httpClientConfig.params())
            .contains(entry(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES));
}

From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolProvider.java

public static HttpClient genClient(PoolType poolConf) {

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager();

    cm.setDefaultMaxPerRoute(poolConf.getHttpConnManagerMaxPerRoute());
    cm.setMaxTotal(poolConf.getHttpConnManagerMaxTotal());

    //Set all the params up front, instead of mutating them? Maybe this matters
    HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, poolConf.getHttpSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, poolConf.getHttpConnectionTimeout());
    params.setParameter(CoreConnectionPNames.TCP_NODELAY, poolConf.isHttpTcpNodelay());
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, poolConf.getHttpConnectionMaxHeaderCount());
    params.setParameter(CoreConnectionPNames.MAX_LINE_LENGTH, poolConf.getHttpConnectionMaxLineLength());
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, poolConf.getHttpSocketBufferSize());
    params.setBooleanParameter(CHUNKED_ENCODING_PARAM, poolConf.isChunkedEncoding());

    final String uuid = UUID.randomUUID().toString();
    params.setParameter(CLIENT_INSTANCE_ID, uuid);

    //Pass in the params and the connection manager
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    SSLContext sslContext = ProxyUtilities.getTrustingSslContext();
    SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = cm.getSchemeRegistry();
    Scheme scheme = new Scheme("https", DEFAULT_HTTPS_PORT, ssf);
    registry.register(scheme);//from  w  w w  .j ava 2s.  c o m

    client.setKeepAliveStrategy(new ConnectionKeepAliveWithTimeoutStrategy(poolConf.getKeepaliveTimeout()));

    LOG.info("HTTP connection pool {} with instance id {} has been created", poolConf.getId(), uuid);

    return client;
}

From source file:io.restassured.config.HttpClientConfigTest.java

@Test
public void setParamsRespectsOtherConfigurationSettings() {
    final HttpClientConfig httpClientConfig = new HttpClientConfig()
            .setParam(ClientPNames.MAX_REDIRECTS, CUSTOM_MAX_REDIRECTS).reuseHttpClientInstance()
            .setParam(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    assertThat(httpClientConfig.params()).contains(entry(ClientPNames.MAX_REDIRECTS, CUSTOM_MAX_REDIRECTS),
            entry(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY));
    assertTrue(httpClientConfig.isConfiguredToReuseTheSameHttpClientInstance());

}

From source file:com.almende.util.ApacheHttpClient.java

/**
 * Instantiates a new apache http client.
 * /*from w ww  .j av a2  s.com*/
 */
private ApacheHttpClient() {

    // generate httpclient
    httpClient = new DefaultHttpClient();

    // Set cookie policy and persistent cookieStore
    try {
        httpClient.setCookieStore(new MyCookieStore());
    } catch (final Exception e) {
        LOG.log(Level.WARNING, "Failed to initialize persistent cookieStore!", e);
    }
    final HttpParams params = httpClient.getParams();

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    httpClient.setParams(params);
}

From source file:org.mobicents.servlet.sip.restcomm.interpreter.http.HttpRequestExecutor.java

public HttpResponseDescriptor execute(final HttpRequestDescriptor request) throws ClientProtocolException,
        IllegalArgumentException, UnsupportedEncodingException, IOException, URISyntaxException {
    int statusCode = -1;
    HttpResponse response = null;//from   w  w w  . j  a  va2 s.  co m
    HttpRequestDescriptor descriptor = request;
    do {
        final DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        response = new DefaultHttpClient().execute(descriptor.getHttpRequest());
        statusCode = response.getStatusLine().getStatusCode();
        if (isRedirect(statusCode)) {
            final Header locationHeader = response.getFirstHeader("Location");
            if (locationHeader != null) {
                final String redirectLocation = locationHeader.getValue();
                final URI uri = URI.create(redirectLocation);
                descriptor = new HttpRequestDescriptor(uri, descriptor.getMethod(), descriptor.getParameters());
                continue;
            } else {
                break;
            }
        }
    } while (isRedirect(statusCode));
    return response(descriptor, response);
}

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