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

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

Introduction

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

Prototype

String BROWSER_COMPATIBILITY

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

Click Source Link

Document

The policy that provides high degree of compatibilty with common cookie management of popular HTTP agents.

Usage

From source file:com.hsbc.frc.SevenHero.ClientProxyAuthentication.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from   w  ww. ja v a  2s .c  om
        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:Main.java

public static DefaultHttpClient getDefaultHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params);

    HttpConnectionParams.setSoTimeout(defaultHttpClient.getParams(), SOCKET_TIME_OUT);
    HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), CONNECTION_TIME_OUT);
    defaultHttpClient.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 10);
    HttpClientParams.setCookiePolicy(defaultHttpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpProtocolParams.setUserAgent(defaultHttpClient.getParams(),
            "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.18) Gecko/20110628 Ubuntu/10.04 (lucid) Firefox/3.6.18");
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
    return defaultHttpClient;
}

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
 *//*from ww w .  ja  va  2 s  .  c  o m*/
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 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 w  w. j a va2s  .c  o  m
 */
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:de.koczewski.maxapi.RequestExecutor.java

public RequestExecutor() {
    httpClient = WebClientDevWrapper.createClient();
    // HttpProtocolParams.setUserAgent(httpClient.getParams(),
    // "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
}

From source file:ilarkesto.integration.max.internet.RequestExecutor.java

public RequestExecutor(DefaultHttpClient httpClient) {
    this.httpClient = httpClient;
    // HttpProtocolParams.setUserAgent(httpClient.getParams(),
    // "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1");
    HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
}

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 ww w .  j  a  v  a2 s.c  o 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:org.ptlug.ptwifiauth.UserSession.java

public int getDefaultUrl() {
    try {/*from  ww  w . j  a  v a 2s.c  o m*/

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpget.getParams().setParameter("http.protocol.handle-redirects", false);
        last_response = httpclient.execute(httpget);

        this.debugCookies();

        String html = getHtmlContent();

        Logger.getInstance().doLog("HTMLLOGIN", html);

        if (html.contains("The document has moved")) {
            return 4;
        }

        if (html.contains("<h2>Please")) {
            int token_id = html.indexOf("<h2>Please");

            String addr = html.substring(token_id, html.length());

            GlobalSpace.login_url = addr.split("'")[1];

            Logger.getInstance().doLog("HTMLREDIRECT", "" + addr.split("'")[1]);

            httppost = new HttpPost(GlobalSpace.login_url);

            return 1;
        }

        // else
        // AppConsts.login_url = "http://wifi.ptlug.org/login";

        return 0; // SET 1 ONLY FOR TESTING!!!

    }

    catch (ClientProtocolException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "ClientProtocolException " + e.toString());
        return 2;
    }

    catch (IOException e) {
        Logger.getInstance().doLog(LogConsts.login_result, "IOException " + e.toString());
        return 2;
    }
}

From source file:com.traffic.common.utils.http.HttpClientUtils.java

/**
 * ,result""/*from w ww . j av a  2s. co m*/
 * 
 * @param url
 * @param param
 * @return
 */
public static String httpPost(String url, String paramvalue) {
    logger.info("httpPost URL [" + url + "] start ");
    if (logger.isDebugEnabled()) {
        logger.debug("httpPost body :" + paramvalue);
    }
    logger.info("httpPost body :" + paramvalue);
    HttpClient httpclient = null;
    HttpPost httpPost = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    String result = "";

    try {
        httpclient = HttpConnectionManager.getHttpClient();
        // cookie---??
        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpPost = new HttpPost(url);
        // ???
        for (Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }

        StringEntity stringEntity = new StringEntity(paramvalue, "UTF-8");
        httpPost.setEntity(stringEntity);

        // 
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 40000);
        // ?
        HttpConnectionParams.setSoTimeout(httpPost.getParams(), 200000);
        response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("HttpStatus ERROR" + "Method failed: " + response.getStatusLine());
            return "";
        } else {
            entity = response.getEntity();
            if (null != entity) {
                byte[] bytes = EntityUtils.toByteArray(entity);
                result = new String(bytes, "UTF-8");
            } else {
                logger.error("httpPost URL [" + url + "],httpEntity is null.");
            }
            return result;
        }
    } catch (Exception e) {
        logger.error("httpPost URL [" + url + "] error, ", e);
        return "";
    }
}