Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

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

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:org.jboss.as.test.clustering.cluster.web.authentication.BasicAuthenticationWebFailoverTestCase.java

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, URISyntaxException {

    CredentialsProvider provider = new BasicCredentialsProvider();
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build();

    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);

    try {/*from  ww  w  . ja va 2 s .  co  m*/
        // Valid login, invalid role
        setCredentials(provider, "forbidden", "password", baseURL1, baseURL2);
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Invalid login, valid role
        setCredentials(provider, "allowed", "bad", baseURL1, baseURL2);
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        // Valid login, valid role
        setCredentials(provider, "allowed", "password", baseURL1, baseURL2);
        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        undeploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }

        deploy(DEPLOYMENT_1);

        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:org.alfresco.provision.TestReleaseDeployInfo.java

public TestReleaseDeployInfo(String bmDriverHostname, String bmDriverPort, String username, String password,
        String warFilename, String bmServerHostname, String bmServerPort, String testName,
        String testDescription) throws Exception {
    int idx1 = warFilename.lastIndexOf("/");
    int idx2 = warFilename.lastIndexOf(".");
    this.release = warFilename.substring(idx1 + 1, idx2);
    this.warFilename = warFilename;
    this.bmDriverHostname = bmDriverHostname;
    this.bmDriverPort = bmDriverPort;
    this.username = username;
    this.password = password;
    this.bmServerHostname = bmServerHostname;
    this.bmServerPort = bmServerPort;
    this.testName = testName;
    this.testDescription = testDescription;
    this.schema = getSchema();

    HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
    this.client = HttpClients.custom().setConnectionManager(poolingConnManager).build();

    final MongoDbFactory factory = new MongoDbFactory();
    factory.setMongoURI("mongodb://" + bmServerHostname + ":27017");
    factory.setDbName("bm20-config");
    final DB db = factory.createInstance();
    this.testDAO = new MongoTestDAO(db);
}

From source file:com.adobe.ags.curly.ConnectionManager.java

public CloseableHttpClient getAuthenticatedClient(CredentialsProvider creds) {
    resetConnectionManager(httpPoolSize);
    return HttpClients.custom().setDefaultCredentialsProvider(creds).setDefaultCookieStore(cookieStore)
            .setConnectionManager(connectionManager).setConnectionManagerShared(true)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:org.apache.vxquery.rest.AbstractRestServerTest.java

/**
 * Submit a {@link QueryRequest} and fetth the resulting
 * {@link AsyncQueryResponse}//from   w  ww. j  a v a 2  s.  c  o  m
 *
 * @param uri
 *            uri of the GET request
 * @param accepts
 *            application/json | application/xml
 * @param method
 *            Http Method to be used to send the request
 * @return Response received for the query request
 * @throws Exception
 */
protected static <T> T getQuerySuccessResponse(URI uri, String accepts, Class<T> type, String method)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionTimeToLive(20, TimeUnit.SECONDS).build();

    try {
        HttpUriRequest request = getRequest(uri, method);

        if (accepts != null) {
            request.setHeader(HttpHeaders.ACCEPT, accepts);
        }

        try (CloseableHttpResponse httpResponse = httpClient.execute(request)) {
            Assert.assertEquals(HttpResponseStatus.OK.code(), httpResponse.getStatusLine().getStatusCode());
            if (accepts != null) {
                Assert.assertEquals(accepts, httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
            }

            HttpEntity entity = httpResponse.getEntity();
            Assert.assertNotNull(entity);

            String response = RestUtils.readEntity(entity);
            return RestUtils.mapEntity(response, type, accepts);
        }
    } finally {
        HttpClientUtils.closeQuietly(httpClient);
    }
}

From source file:com.vmware.bdd.cli.http.HttpClientProvider.java

@Bean(name = SECURE_HTTP_CLIENT)
@Qualifier(SECURE_HTTP_CLIENT)//  www . ja v  a 2s  . c  o m
public HttpClient secureHttpClient()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext sslContext = SSLContexts.custom().useTLS().build();

    sslContext.init(null, new TrustManager[] { trustManager }, null);

    String[] supportedProtocols = cliProperties.getSupportedProtocols();
    String[] supportedCipherSuites = cliProperties.getSupportedCipherSuites();
    String hostnameVerifier = cliProperties.getHostnameVerifier();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("supported protocols: " + ArrayUtils.toString(supportedProtocols));
        LOGGER.debug("supported cipher suites: " + ArrayUtils.toString(supportedCipherSuites));
        LOGGER.debug("hostname verifier: " + hostnameVerifier);
    }

    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols,
            supportedCipherSuites, getHostnameVerifier(hostnameVerifier));

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", socketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(20);
    cm.setDefaultMaxPerRoute(10);
    //      HttpHost proxy = new HttpHost("127.0.0.1", 8810, "http");
    //      HttpClient  client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).setProxy(proxy).build();

    HttpClient client1 = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    return client1;
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {//from  ww  w.  j  a v  a  2  s. co  m
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}

From source file:com.kugou.opentsdb.OpenTsdb.java

private OpenTsdb(String hostname, int port, int connectionTimeout, int connectionRequestTimeout,
        int batchSizeLimit) {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(connectionTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout).setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .build();/*from w  ww.  j  av a 2  s .  c o m*/

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    cm.setMaxTotal(MAX_CONNECTIONS_TOTAL);
    client = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(config).build();
    host = new HttpHost(hostname, port);
    this.batchSizeLimit = batchSizeLimit;
    this.connectionTimeout = connectionTimeout;
    this.connectionRequestTimeout = connectionRequestTimeout;
}

From source file:org.kaaproject.kaa.server.verifiers.gplus.verifier.GplusUserVerifier.java

@Override
public void start() {
    LOG.info("user verifier started");
    threadPool = new ThreadPoolExecutor(configuration.getMinParallelConnections(),
            configuration.getMaxParallelConnections(), configuration.getKeepAliveTimeMilliseconds(),
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(configuration.getMaxParallelConnections());
    httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
}

From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java

/**
 * Construct the client with {@link SSLContext} to handle HTTPS request properly.
 * @param sslContext/*  ww  w .java2  s .  com*/
 */
public FileUploadDownloadClient(SSLContext sslContext) {
    _httpClient = HttpClients.custom().setSSLContext(sslContext).build();
}

From source file:org.apache.jena.fuseki.embedded.TestFusekiTestAuth.java

@Test(expected = HttpException.class)
public void testServer_auth_bad_password() {
    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, "WRONG"));
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();

    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    } catch (HttpException ex) {
        throw assertAuthHttpException(ex);
    }/*w w w .  j av a2 s.c  o  m*/
}