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.mycontroller.restclient.core.RestHttpClient.java

protected CloseableHttpClient getHttpClient() {
    return HttpClients.custom().setDefaultRequestConfig(customRequestConfig).build();
}

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);
        }/* ww  w  . j  av a 2 s .  c  o  m*/
    }
    httpClient = httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()).build();

}

From source file:org.commonjava.util.jhttpc.HttpFactory.java

public CloseableHttpClient createClient(final SiteConfig location) throws JHttpCException {
    CloseableHttpClient client;//from   w  w  w .j  a  v a 2  s.co m
    if (location != null) {
        HttpClientBuilder builder = HttpClients.custom();

        if (authenticator != null) {
            builder = authenticator.decorateClientBuilder(builder);
        }

        logger.debug("Using site config: {} for advanced client options", location);
        SiteConnectionConfig connConfig = new SiteConnectionConfig(location);

        final SSLConnectionSocketFactory sslFac = createSSLSocketFactory(location);
        if (sslFac != null) {
            //                HostnameVerifier verifier = new SSLHostnameVerifierImpl( );
            //                builder.setSSLHostnameVerifier( verifier );
            builder.setSSLSocketFactory(sslFac);
            connConfig.withSSLConnectionSocketFactory(sslFac);
        }

        ConnectionManagerTracker managerWrapper = connectionCache.getTrackerFor(connConfig);
        builder.setConnectionManager(managerWrapper.acquire());

        if (location.getProxyHost() != null) {
            final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(
                    new HttpHost(location.getProxyHost(), getProxyPort(location)));
            builder.setRoutePlanner(planner);
        }

        final int timeout = 1000 * location.getRequestTimeoutSeconds();
        builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
                .setSocketTimeout(timeout).setConnectTimeout(timeout).build());

        client = new TrackedHttpClient(builder.build(), managerWrapper);
        //            client = builder.build();
    } else {
        client = HttpClients.createDefault();
    }

    return client;
}

From source file:com.microsoft.azure.hdinsight.spark.common.SparkBatchSubmission.java

/**
 * create batch sp  ark job/* w  w w. j  av a 2s .co m*/
 * @param connectUrl : eg http://localhost:8998/batches
 * @param submissionParameter : spark submission parameter
 * @return response result
 */
public HttpResponse createBatchSparkJob(String connectUrl, SparkSubmissionParameter submissionParameter)
        throws IOException {
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider)
            .build();
    HttpPost httpPost = new HttpPost(connectUrl);
    httpPost.addHeader("Content-Type", "application/json");
    httpPost.addHeader("User-Agent", UserAgentName);
    StringEntity postingString = new StringEntity(submissionParameter.serializeToJson());
    httpPost.setEntity(postingString);
    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        return StreamUtil.getResultFromHttpResponse(response);
    }
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public <Result> Result executePost(String query, HttpEntity content,
        final Function<String, Result> responseConverter) throws ClientProtocolException, IOException {

    CloseableHttpClient client = HttpClients.custom().build();

    HttpUriRequest request = RequestBuilder.post().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).addHeader(createSecurityHeader()).setEntity(content).build();

    return client.execute(request, new ResponseHandler<Result>() {

        @Override//from   ww w  . java  2s .co  m
        public Result handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            return responseConverter.apply(IOUtils.toString(response.getEntity().getContent()));
        }
    });
}

From source file:projekat.rest_client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() {

    fillTypesForRestService();//w  ww .  ja  v a 2 s.co  m
    //za potrebe testirnja
    if (rest_keystore == null || "".equals(rest_keystore)) {
        rest_keystore = "/etc/keystores/nst2.jks";
        rest_keystore_password = "changeit";
        res_host_port = "8443";
        rest_hostname = "localhost";
    }
    InputStream keyStoreInputStream = null;
    try {
        keyStoreInputStream = new FileInputStream(rest_keystore);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("");
        }
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(keyStoreInputStream, rest_keystore_password.toCharArray());
        } finally {
            keyStoreInputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        auth = new HttpComponentsClientHttpRequestFactoryBasicAuth(
                new HttpHost(rest_hostname, Integer.parseInt(res_host_port), "https"), httpClient);
        auth.setConnectTimeout(60000);
        auth.setReadTimeout(180000);
        restTemplate = new RestTemplate(auth);
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | KeyManagementException ex) {
        Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            keyStoreInputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.frontcache.client.FrontCacheClient.java

private FrontCacheClient(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION_TIMEOUT)
            .setConnectTimeout(CONNECTION_TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override/* w  ww.ja  v a 2  s .c o m*/
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}

From source file:org.apache.hadoop.gateway.service.test.ServiceTestResource.java

@GET
@Produces({ APPLICATION_XML, APPLICATION_JSON })
public ServiceTestWrapper serviceTest(@QueryParam("username") String username,
        @QueryParam("password") String password) {
    List<ServiceTest> tests = new ArrayList<>();
    List<String> messages = new ArrayList<>();
    String authString;//from w w w.  j  a  v  a  2 s .c om
    GatewayConfig config = (GatewayConfig) request.getServletContext()
            .getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE);
    SSLContext ctx = null;
    CloseableHttpClient client;
    String id = getTopologyName();

    Topology topology = getTopology(id);

    //    Create Authorization String
    if (username != null && password != null) {
        authString = "Basic " + Base64.encodeAsString((username + ":" + password).getBytes());
    } else if (request.getHeader("Authorization") != null) {
        authString = request.getHeader("Authorization");
    } else {
        authString = null;
    }

    //    Attempt to build SSL context for HTTP client.
    try {
        ctx = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        messages.add(e.getMessage());
    }

    //    Initialize the HTTP client
    if (ctx == null) {
        client = HttpClients.createDefault();
    } else {
        client = HttpClients.custom().setSslcontext(ctx).build();
    }

    if (topology != null) {
        for (Service s : topology.getServices()) {
            List<String> urls = getServiceTestURLs(config, s.getRole(), topology);

            //          Make sure we handle a case where no URLs are found.
            if (urls.size() <= 0) {
                ServiceTest test = new ServiceTest(s);
                test.setMessage("This service did not contain any test URLs");
            }

            for (String url : urls) {
                HttpGet req = new HttpGet();
                ServiceTest test = new ServiceTest(s, url);

                if (authString != null) {
                    req.setHeader("Authorization", authString);
                } else {
                    messages.add("No credentials provided. Expect HTTP 401 responses.");
                }

                try {
                    req.setURI(new URIBuilder(url).build());
                    CloseableHttpResponse res = client.execute(req);
                    String contentLength = "Content-Length:" + res.getEntity().getContentLength();
                    String contentType = (res.getEntity().getContentType() != null)
                            ? res.getEntity().getContentType().toString()
                            : "No-contenttype";
                    test.setResponseContent(contentLength + "," + contentType);
                    test.setHttpCode(res.getStatusLine().getStatusCode());
                    res.close();

                } catch (IOException e) {
                    messages.add("Exception: " + e.getMessage());
                    test.setMessage(e.getMessage());
                } catch (URISyntaxException e) {
                    test.setMessage(e.getMessage());
                } catch (Exception e) {
                    messages.add(e.getMessage());
                    test.setMessage(e.getMessage());
                } finally {
                    req.releaseConnection();
                    tests.add(test);
                }
            }
        }
    } else {
        messages.add("Topology " + id + " not found");
    }

    try {
        client.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ServiceTestWrapper stw = new ServiceTestWrapper();
    stw.setTests(tests);
    stw.setMessages(messages);

    return stw;
}

From source file:ph.com.globe.connect.HttpRequest.java

/**
 * Sends get request to the specified url.
 * /*from  ww  w.  ja  v a  2s . c o  m*/
 * @return CloseableHttpResponse
 * @throws HttpRequestException http request exception
 */
public CloseableHttpResponse sendGet() throws HttpRequestException {

    // try building up
    try {
        // initialize ssl context builder
        SSLContextBuilder builder = new SSLContextBuilder();

        // set trust self signed strategy
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // initialize ssl socket connection factory
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());

        // default http client
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

        // create request method
        HttpGet request = new HttpGet(this.url);

        // set default header
        request.setHeader("User-Agent", this.USER_AGENT);

        // try request
        try {
            // execute request and get response
            CloseableHttpResponse response = client.execute(request);

            return response;
        } catch (IOException e) {
            throw new HttpRequestException(e.getMessage());
        }
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new HttpRequestException(e.getMessage());
    }
}

From source file:org.wildfly.test.integration.elytron.http.PasswordMechTestBase.java

@Test
public void testInvalidPrincipal() throws Exception {
    HttpGet request = new HttpGet(new URI(url.toExternalForm() + "role1"));
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user1wrong", "password1");

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {//from w  ww  .  j  a  v a 2s  .  c om
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            assertEquals("Unexpected status code in HTTP response.", SC_UNAUTHORIZED, statusCode);
        }
    }
}