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.osgpfoundation.osgp.webdemoapp.infra.platform.SoapRequestHelper.java

/**
 * Creates a HttpComponentsMessageSender for communication with the
 * platform.//from   ww w  .j ava 2 s.co m
 *
 * @return HttpComponentsMessageSender
 */
private HttpComponentsMessageSender createHttpMessageSender() {

    final HttpComponentsMessageSender sender = new HttpComponentsMessageSender();

    final HttpClientBuilder builder = HttpClients.custom();
    builder.addInterceptorFirst(new ContentLengthHeaderRemoveInterceptor());
    try {
        final SSLContext sslContext = new SSLContextBuilder()
                .loadKeyMaterial(this.keyStoreHelper.getKeyStore(), this.keyStoreHelper.getKeyStorePwAsChar())
                .loadTrustMaterial(this.keyStoreHelper.getTrustStore()).build();
        final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
        builder.setSSLSocketFactory(sslConnectionFactory);
        sender.setHttpClient(builder.build());
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException e) {
        e.printStackTrace();
    }

    return sender;
}

From source file:com.github.vbauer.yta.service.transport.impl.RestClientImpl.java

private HttpClient createClient() throws Exception {
    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_TIMEOUT)
            .setConnectTimeout(DEFAULT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_TIMEOUT)
            .setRedirectsEnabled(true).build();

    return HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .setSSLSocketFactory(socketFactory).setDefaultRequestConfig(requestConfig).build();
}

From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java

/**
 * Prepare connection/*w w w  .  j av a  2s .c  o m*/
 *
 * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception
 */
@Override
public void prepareConnection() throws EWSHttpException {
    try {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setConnectionManager(this.httpClientConnMng);

        //create the cookie store
        if (cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        builder.setDefaultCookieStore(cookieStore);

        if (getProxy() != null) {
            HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort());
            builder.setProxy(proxy);

            if (HttpProxyCredentials.isProxySet()) {
                NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(),
                        HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxy), cred);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
        }
        if (getUserName() != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(AuthScope.ANY,
                    new NTCredentials(getUserName(), getPassword(), "", getDomain()));
            builder.setDefaultCredentialsProvider(credsProvider);
        }

        //fix socket config
        SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build();
        builder.setDefaultSocketConfig(sc);

        RequestConfig.Builder rcBuilder = RequestConfig.custom();
        rcBuilder.setAuthenticationEnabled(true);
        rcBuilder.setConnectionRequestTimeout(getTimeout());
        rcBuilder.setConnectTimeout(getTimeout());
        rcBuilder.setRedirectsEnabled(isAllowAutoRedirect());
        rcBuilder.setSocketTimeout(getTimeout());

        // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials
        if (getUserName() != null) {
            ArrayList<String> authPrefs = new ArrayList<String>();
            authPrefs.add(AuthSchemes.NTLM);
            rcBuilder.setTargetPreferredAuthSchemes(authPrefs);
        }
        //
        builder.setDefaultRequestConfig(rcBuilder.build());

        httpPostReq = new HttpPost(getUrl().toString());
        httpPostReq.addHeader("Content-type", getContentType());
        //httpPostReq.setDoAuthentication(true);
        httpPostReq.addHeader("User-Agent", getUserAgent());
        httpPostReq.addHeader("Accept", getAccept());
        httpPostReq.addHeader("Keep-Alive", "300");
        httpPostReq.addHeader("Connection", "Keep-Alive");

        if (isAcceptGzipEncoding()) {
            httpPostReq.addHeader("Accept-Encoding", "gzip,deflate");
        }

        if (getHeaders().size() > 0) {
            for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) {
                httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue());
            }
        }

        //create the client
        client = builder.build();
    } catch (Exception er) {
        er.printStackTrace();
    }
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private static CloseableHttpClient createHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(SSL_SOCKET_FACTORY);
    return httpClientBuilder.build();
}

From source file:ai.susi.server.ClientConnection.java

/**
  * GET request//from  w w w.j av  a 2s .  c  o m
  * @param urlstring
  * @param useAuthentication
  * @throws IOException
  */
public ClientConnection(String urlstring, boolean useAuthentication) throws IOException {
    this.httpClient = HttpClients.custom().useSystemProperties()
            .setConnectionManager(getConnctionManager(useAuthentication))
            .setDefaultRequestConfig(defaultRequestConfig).build();
    this.request = new HttpGet(urlstring);
    this.request.setHeader("User-Agent", USER_AGENT);
    this.init();
}

From source file:com.emc.storageos.driver.dellsc.scapi.rest.RestClient.java

/**
 * Instantiates a new Rest client./* w  w  w  .j a v  a  2s  .  c  o m*/
 *
 * @param host Host name or IP address of the Dell Storage Manager server.
 * @param port Port the DSM data collector is listening on.
 * @param user The DSM user name to use.
 * @param password The DSM password.
 */
public RestClient(String host, int port, String user, String password) {
    this.baseUrl = String.format("https://%s:%d/api/rest", host, port);

    try {
        // Set up auth handling
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, password));
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost target = new HttpHost(host, port, "https");
        authCache.put(target, basicAuth);

        // Set up our context
        httpContext = HttpClientContext.create();
        httpContext.setCookieStore(new BasicCookieStore());
        httpContext.setAuthCache(authCache);

        // Create our HTTPS client
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        this.httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setDefaultCredentialsProvider(credsProvider).setSSLSocketFactory(sslSocketFactory).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        // Hopefully default SSL handling is set up
        LOG.warn("Failed to configure HTTP handling, falling back to default handler.");
        LOG.debug("Config error: {}", e);
        this.httpClient = HttpClients.createDefault();
    }
}

From source file:edu.mit.scratch.ScratchProject.java

public boolean comment(final ScratchSession session, final String comment) throws ScratchProjectException {
    final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    final CookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
    final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID());
    final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken());
    final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
    lang.setDomain(".scratch.mit.edu");
    lang.setPath("/");
    sessid.setDomain(".scratch.mit.edu");
    sessid.setPath("/");
    token.setDomain(".scratch.mit.edu");
    token.setPath("/");
    debug.setDomain(".scratch.mit.edu");
    debug.setPath("/");
    cookieStore.addCookie(lang);//from  ww  w .  j  a v a2  s.c o  m
    cookieStore.addCookie(sessid);
    cookieStore.addCookie(token);
    cookieStore.addCookie(debug);

    final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                    + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
            .setDefaultCookieStore(cookieStore).build();
    CloseableHttpResponse resp;

    final JSONObject obj = new JSONObject();
    obj.put("content", comment);
    obj.put("parent_id", "");
    obj.put("commentee_id", "");
    final String strData = obj.toString();

    HttpUriRequest update = null;
    try {
        update = RequestBuilder.post()
                .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID() + "/add/")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/")
                .addHeader("Origin", "https://scratch.mit.edu/")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest")
                .addHeader("Cookie",
                        "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken="
                                + session.getCSRFToken())
                .addHeader("X-CSRFToken", session.getCSRFToken()).setEntity(new StringEntity(strData)).build();
    } catch (final UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    try {
        resp = httpClient.execute(update);
        System.out.println("cmntadd:" + resp.getStatusLine());
        final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("cmtline:" + result.toString());
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    BufferedReader rd;
    try {
        rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    } catch (UnsupportedOperationException | IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return false;
}

From source file:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java

@Override
protected void deploy(List<Binary> binaries, Run run) throws IOException {
    CloseableHttpClient client = null;/*from   w  w w .  j a  va 2  s.  c o m*/
    try {
        if (credentialsId == null || credentialsId.isEmpty()) {
            client = HttpClients.createDefault();
        } else {
            BasicCredentialsProvider credentials = new BasicCredentialsProvider();
            StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById(
                    credentialsId, StandardUsernamePasswordCredentials.class, run,
                    Lists.<DomainRequirement>newArrayList());
            credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    credentialById.getUsername(), credentialById.getPassword().getPlainText()));

            client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries()
                    .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build();
        }

        for (Binary binary : binaries) {
            BufferedHttpEntity entity = new BufferedHttpEntity(
                    new InputStreamEntity(binary.getFile().open(), binary.getFile().length()));
            HttpPost post = new HttpPost(remoteLocation + binary.getName());
            post.setEntity(entity);

            CloseableHttpResponse response = null;
            try {
                response = client.execute(post);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    log.fine("Deployed " + binary.getName() + " to " + remoteLocation);
                } else {
                    log.warning("Cannot deploy file " + binary.getName() + ". Response from target was "
                            + statusCode);
                    run.setResult(Result.FAILURE);
                    throw new IOException(response.getStatusLine().toString());
                }
            } finally {
                if (response != null) {
                    response.close();
                }
            }
        }
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.vmware.bdd.plugin.clouderamgr.poller.host.HostInstallPoller.java

@Override
public void setup() {
    try {// w w  w  .  j a v a  2s.  c o  m
        login();
        httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(20);
        this.httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setConnectionManager(httpClientConnectionManager).build();
        int maxSessionNum = 10;
        int i = 0;
        reported = true;
        executor = Executors.newCachedThreadPool();
        for (final ApiCommand command : rootResource.getCommandsResource().readCommand(parentCmdId)
                .getChildren()) {
            /* Each crawler will launch a http session with CM server and keep on requesting.
             * So far, we only report cluster level status, so it's no need to monitor each subcommand,
             * especially for large scale cluster.
             */
            if (i == maxSessionNum) {
                break;
            }
            executor.submit(new Crawler(command.getId()));
            i += 1;
        }
    } catch (Exception e) {
        // As this implementation does not follow official APIs, may not work
        // in future version, just ignore any exception
    }
}