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:se.curity.examples.http.UnsafeHttpClientSupplier.java

private static HttpClient create() {
    try {/*from w w  w .  ja v  a  2  s .c o  m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                NoopHostnameVerifier.INSTANCE);
        return HttpClients.custom().disableAuthCaching().disableAutomaticRetries().disableRedirectHandling()
                .setSSLSocketFactory(sslSocketFactory).build();
    } catch (Exception e) {
        _logger.error("Unable to create Unsafe HTTP client supplier", e);
        throw new RuntimeException("Unable to initialize httpClient", e);
    }
}

From source file:io.uploader.drive.drive.largefile.HttpClientUtils.java

public static CloseableHttpClient getHttpClient(HasProxySettings proxySetting) {
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

    CloseableHttpClient httpclient = null;
    if (proxySetting != null && proxySetting.isActive()) {
        logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")");
        CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider());
        HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpclient = HttpClients.custom().setRoutePlanner(routePlanner)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else {//from   w w w .  j  a  v  a  2 s  . co  m
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}

From source file:io.fabric8.maven.support.Apps.java

/**
 * Posts a file to the git repository// w ww. j  a  v a 2  s.c  om
 */
public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl,
        String branch, String path, Logger logger) throws URISyntaxException, IOException {
    HttpClientBuilder builder = HttpClients.custom();
    if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443),
                new UsernamePasswordCredentials(user, password));
        builder = builder.setDefaultCredentialsProvider(credsProvider);
    }

    CloseableHttpClient client = builder.build();
    try {

        String url = consoleUrl;
        if (!url.endsWith("/")) {
            url += "/";
        }
        url += "git/";
        url += branch;
        if (!path.startsWith("/")) {
            url += "/";
        }
        url += path;

        logger.info("Posting App Zip " + file.getName() + " to " + url);
        URI buildUrl = new URI(url);
        HttpPost post = new HttpPost(buildUrl);

        // use multi part entity format
        FileBody zip = new FileBody(file);
        HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build();
        post.setEntity(entity);
        // post.setEntity(new FileEntity(file));

        HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post);
        logger.info("Response: " + response);
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode < 200 || statusCode >= 300) {
                throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response);
            }
        }
        return response;
    } finally {
        Closeables.closeQuietly(client);
    }
}

From source file:org.springframework.cloud.config.server.support.HttpClientSupport.java

public static HttpClientBuilder builder(HttpEnvironmentRepositoryProperties environmentProperties)
        throws GeneralSecurityException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    if (environmentProperties.isSkipSslValidation()) {
        sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
        httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }/*  w  w  w. j  a v  a 2  s .  co  m*/

    if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
        ProxyHostProperties httpsProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTPS);
        ProxyHostProperties httpProxy = environmentProperties.getProxy()
                .get(ProxyHostProperties.ProxyForScheme.HTTP);

        httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
        httpClientBuilder
                .setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
    } else {
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
        httpClientBuilder.setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider());
    }

    int timeout = environmentProperties.getTimeout() * 1000;
    return httpClientBuilder.setSSLContext(sslContextBuilder.build()).setDefaultRequestConfig(
            RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
}

From source file:org.drftpd.util.HttpUtils.java

public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent).build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);//from  w ww.ja  va 2 s .  co m
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}

From source file:com.atanas.kanchev.testframework.dataservices.api.rest.executor.Executor.java

/**
 * <p>Configure custom cClient.</p>
 *
 * @return a {@link org.apache.http.impl.client.HttpClientBuilder} object.
 *///from  w w w .  j av  a2s  .  com
public static HttpClientBuilder confClient() {

    return httpClientBuilder = HttpClients.custom();
}

From source file:network.ProxiedHttpClientAdaptor.java

public ProxiedHttpClientAdaptor(HttpHost proxy) {

    super();/* w  w  w.j av  a  2  s  . c  o  m*/

    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    this.httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build();
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogle(URI newurl) throws IOException, InterruptedException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    int count = 0;
    try {/*from www .  ja  v  a2 s  .  co  m*/
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        System.out.println("Response status " + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("403")
                || responsestatus.contains("400") || responsestatus.contains("407")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || "".equals(responsestatus)) {
            Thread.sleep(10000);
            do {
                count++;
                responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                if (responsebody == null) {
                    Thread.sleep(10000);
                    System.out.println("PROX FAILURE");
                }
                if (count > 20) {
                    Thread.sleep(1000);
                    break;
                }
            } while (responsebody == null || "".equals(responsebody));
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        System.out.println("Exception = " + e);
        do {
            count++;
            responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
            if (responsebody == null) {
                System.out.println("PROX FAILURE");
            }
            if (count > 15) {
                Thread.sleep(50000);
                //                    responsebody = fetchPageSourcefromClientGoogleSecond(newurl);
                break;
            }
        } while (responsebody == null || "".equals(responsebody));
    } finally {
        httpclient.close();
    }
    return responsebody;
}

From source file:org.wso2.security.tools.product.manager.handler.HttpRequestHandler.java

/**
 * Send HTTP GET request/*from w  w w.  jav a2s  .c  o m*/
 *
 * @param request Requested URI
 * @return HTTPResponse after executing the command
 */
public static HttpResponse sendGetRequest(URI request) {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        HttpClient httpClient = clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .build();
        HttpGet httpGetRequest = new HttpGet(request);
        return httpClient.execute(httpGetRequest);
    } catch (IOException e) {
        LOGGER.error("Error occurred while sending GET request to " + request.getPath(), e);
    }
    return null;
}

From source file:tv.icntv.common.HttpClientHolder.java

private static void init() {
    // custom builder
    builder = HttpClients.custom();
    PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    manager.setMaxTotal(DEFAULT_MAX_TOTAL_NUM);
    builder.setConnectionManager(manager);
    builder.setMaxConnPerRoute(DEFAULT_MAX_NUM_PER_ROUTE);
    builder.setMaxConnTotal(DEFAULT_MAX_TOTAL_NUM);
    // headers/*  w  ww  .  j  a va2 s  .c  o m*/
    List<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,"
                    + " application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint,"
                    + " application/msword, */*"));
    //        headers.add(new BasicHeader("Content-Type","application/xml"));
    headers.add(new BasicHeader("Accept-Language", "zh-cn,en-us,zh-tw,en-gb,en;"));
    headers.add(new BasicHeader("Accept-Charset", "gbk,gb2312,utf-8,BIG5,ISO-8859-1;"));
    headers.add(new BasicHeader("Connection", "Close"));
    headers.add(new BasicHeader("Cache-Control", "no-cache"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Connection", "close"));
    builder.setDefaultHeaders(headers);
    // retry handler
    builder.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= MAX_EXECUTION_NUM) {
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                return false;
            }
            if (exception instanceof UnknownHostException) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return false;
            }
            if (exception instanceof SSLException) {
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    });

    // build client
    client = builder.build();
}