Example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCookieStore

List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCookieStore

Introduction

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

Prototype

public final HttpClientBuilder setDefaultCookieStore(final CookieStore cookieStore) 

Source Link

Document

Assigns default CookieStore instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:com.glaf.core.util.http.HttpClientUtils.java

public static String doPost(String url, String data, String contentType, String encoding) {
    StringBuffer buffer = new StringBuffer();
    InputStreamReader is = null;// w w  w . ja  va 2 s.c o  m
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        HttpPost post = new HttpPost(url);
        if (data != null) {
            StringEntity entity = new StringEntity(data, encoding);
            post.setHeader("Content-Type", contentType);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

/**
 * ??POST//from  w w w.ja va2  s  .c o  m
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doPost(String url, String encoding, Map<String, String> dataMap) {
    StringBuffer buffer = new StringBuffer();
    HttpPost post = null;
    InputStreamReader is = null;
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        post = new HttpPost(url);
        if (dataMap != null && !dataMap.isEmpty()) {
            List<org.apache.http.NameValuePair> nameValues = new ArrayList<org.apache.http.NameValuePair>();
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues.add(new BasicNameValuePair(name, value));
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValues, encoding);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }

    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        if (post != null) {
            post.releaseConnection();
        }
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

/**
 * ??GET/*from w ww. j a va2  s  .  c  om*/
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doGet(String url, String encoding, Map<String, String> dataMap) {
    StringBuffer buffer = new StringBuffer();
    HttpGet httpGet = null;
    InputStreamReader is = null;
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        if (dataMap != null && !dataMap.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                sb.append("&").append(name).append("=").append(value);
            }
            if (StringUtils.contains(url, "?")) {
                url = url + sb.toString();
            } else {
                url = url + "?xxxx=1" + sb.toString();
            }
        }
        httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        if (httpGet != null) {
            httpGet.releaseConnection();
        }
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:org.jboss.as.test.http.util.TestHttpClientUtils.java

/**
 * Same as {@link TestHttpClientUtils#promiscuousCookieHttpClient()} but instead returns a builder that can be further configured.
 *
 * @return {@link HttpClientBuilder} of the http client that gives free cookies to everybody
 * @see TestHttpClientUtils#promiscuousCookieHttpClient()
 *///from www.j  ava 2  s.  c  om
public static HttpClientBuilder promiscuousCookieHttpClientBuilder() {
    HttpClientBuilder builder = HttpClients.custom();

    RegistryBuilder<CookieSpecProvider> registryBuilder = CookieSpecRegistries.createDefaultBuilder();
    Registry<CookieSpecProvider> promiscuousCookieSpecRegistry = registryBuilder
            .register("promiscuous", new PromiscuousCookieSpecProvider()).build();
    builder.setDefaultCookieSpecRegistry(promiscuousCookieSpecRegistry);

    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("promiscuous").build();
    builder.setDefaultRequestConfig(requestConfig);

    builder.setDefaultCookieStore(new PromiscuousCookieStore());

    return builder;
}

From source file:com.gs.tools.doc.extractor.core.DownloadManager.java

private DownloadManager() {
    logger.info("Init DownloadManager");
    cookieStore = new BasicCookieStore();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCookieStore(cookieStore);

    Collection<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Accept-Language", "en-US,en;q=0.8"));
    //        headers.add(new BasicHeader("Accept-Encoding", 
    //                "gzip,deflate,sdch"));
    clientBuilder.setDefaultHeaders(headers);

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();
    connectionConfigBuilder.setBufferSize(10485760);
    clientBuilder.setDefaultConnectionConfig(connectionConfigBuilder.build());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true);
    socketConfigBuilder.setSoTimeout(3000000);
    clientBuilder.setDefaultSocketConfig(socketConfigBuilder.build());
    logger.info("Create HTTP Client");
    httpClient = clientBuilder.build();/*w w w . j  av  a2  s . c  o  m*/

}

From source file:com.synopsys.integration.blackduck.rest.CredentialsBlackDuckHttpClient.java

@Override
public void populateHttpClientBuilder(HttpClientBuilder httpClientBuilder,
        RequestConfig.Builder defaultRequestConfigBuilder) {
    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    defaultRequestConfigBuilder.setCookieSpec(CookieSpecs.DEFAULT);
}

From source file:test.integ.be.e_contract.cdi.crossconversation.CrossConversationScopedTest.java

@Test
public void testAndroidSessionSeparation() throws Exception {
    String webBrowserTestLocation = this.baseURL + "browser";
    String webBrowserValueLocation = this.baseURL + "value";
    LOGGER.debug("location: {}", webBrowserTestLocation);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient1 = httpClientBuilder.build();

    httpClientBuilder.setDefaultCookieStore(new BasicCookieStore());
    HttpClient webBrowserHttpClient2 = httpClientBuilder.build();

    HttpContext webBrowserHttpContext1 = new BasicHttpContext();
    String webBrowserCode1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserTestLocation);
    String webBrowserValue1 = doGet(webBrowserHttpClient1, webBrowserHttpContext1, webBrowserValueLocation);

    HttpContext webBrowserHttpContext2 = new BasicHttpContext();
    String webBrowserCode2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserTestLocation);
    String webBrowserValue2 = doGet(webBrowserHttpClient2, webBrowserHttpContext2, webBrowserValueLocation);

    assertNotEquals(webBrowserCode1, webBrowserCode2);
    assertNotEquals(webBrowserValue1, webBrowserValue2);

    String androidLocation1 = this.baseURL + "android?androidCode=" + webBrowserCode1;
    String androidValueLocation1 = webBrowserValueLocation + "?androidCode=" + webBrowserCode1;

    HttpClient androidHttpClient = httpClientBuilder.build();

    HttpContext androidHttpContext1 = new BasicHttpContext();
    String androidCode1 = doGet(androidHttpClient, androidHttpContext1, androidLocation1);
    String androidValue1 = doGet(androidHttpClient, androidHttpContext1, androidValueLocation1);

    assertEquals(webBrowserCode1, androidCode1);
    assertEquals(webBrowserValue1, androidValue1);

    String androidLocation2 = this.baseURL + "android?androidCode=" + webBrowserCode2;
    String androidValueLocation2 = webBrowserValueLocation + "?androidCode=" + webBrowserCode2;

    HttpContext androidHttpContext2 = new BasicHttpContext();
    String androidCode2 = doGet(androidHttpClient, androidHttpContext2, androidLocation2);
    String androidValue2 = doGet(androidHttpClient, androidHttpContext2, androidValueLocation2);

    assertEquals(webBrowserCode2, androidCode2);
    assertEquals(webBrowserValue2, androidValue2);
}

From source file:com.hp.mqm.clt.RestClient.java

public RestClient(Settings settings) {
    this.settings = settings;

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    cookieStore = new BasicCookieStore();
    httpClientBuilder.setDefaultCookieStore(cookieStore);
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD)
            .setSocketTimeout(DEFAULT_SO_TIMEOUT).setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);

    // proxy setting
    if (StringUtils.isNotEmpty(settings.getProxyHost())) {
        HttpHost proxy = new HttpHost(settings.getProxyHost(), settings.getProxyPort());
        requestConfigBuilder.setProxy(proxy);
        if (settings.getProxyUser() != null) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(settings.getProxyHost(), settings.getProxyPort()),
                    new UsernamePasswordCredentials(settings.getProxyUser(), settings.getProxyPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }/*w w  w .java2  s  .  c o  m*/
    }
    httpClient = httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()).build();

}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static HttpClientBuilder initClientBuilder() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    builder.setConnectionManager(CONNECTION_MANAGER);
    builder.setDefaultRequestConfig(dfltReqConf);

    // UserAgent/*from w ww. j  av a  2s . com*/
    builder.setUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

    // remove retries; we expect connections to fail; therefore we should not retry
    //builder.disableAutomaticRetries();
    // disable the cookiestore, cause this may cause segfaults and is not needed
    builder.setDefaultCookieStore(null);
    builder.disableCookieManagement();

    // add custom keep alive strategy
    builder.setKeepAliveStrategy(customKeepAliveStrategy());

    // ask for gzip
    builder.addInterceptorLast(new GzipRequestInterceptor());
    // uncompress gzip
    builder.addInterceptorLast(new GzipResponseInterceptor());
    // Proxy
    builder.setRoutePlanner(ProxySettings.RoutePlanner);
    builder.setDefaultCredentialsProvider(ProxySettings.CredsProvider);

    return builder;
}