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

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

Introduction

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

Prototype

public final HttpClientBuilder setSSLSocketFactory(final LayeredConnectionSocketFactory sslSocketFactory) 

Source Link

Document

Assigns LayeredConnectionSocketFactory instance.

Usage

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes HttpGet Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables.  Returns the data payload response as a JSONObject. 
 * /*from w w  w.  j  av  a2  s  .c  o  m*/
 * @param urlQuery
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject getAPI(String urlQuery) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    try {
        HttpGet httpGet = new HttpGet(ePoint + urlQuery);
        m_log.info("Executing request: " + httpGet.getRequestLine());
        CloseableHttpResponse resp = httpClient.execute(httpGet);
        try {
            m_log.info("Respone: " + resp.getStatusLine());
            String jsonResponse = EntityUtils.toString(resp.getEntity()); // json response
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);
        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Builds and executes an HttpPost Request by appending the urlQuery parameter to the 
 * serverHost:serverPort variables and inserting the contents of the payload parameter.
 * Returns the data payload response as a JSONObject. 
 * /*from w w w.  j a v a  2 s.c  o m*/
 * @param urlQuery
 * @param payload
 * @return org.json.simple.JSONObject
 * @throws Exception
 */
public JSONObject postAPI(String urlQuery, String payload) throws Exception {
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    JSONObject data;
    StringEntity payloadEntity = new StringEntity(payload, ContentType.APPLICATION_JSON);
    try {
        HttpPost httpPost = new HttpPost(ePoint + urlQuery);
        m_log.info("Executing request : " + httpPost.getRequestLine());
        m_log.debug("Payload : " + payload);
        httpPost.setEntity(payloadEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            String jsonResponse = EntityUtils.toString(resp.getEntity());
            JSONParser jp = new JSONParser();
            JSONObject jObj = (JSONObject) jp.parse(jsonResponse);
            data = (JSONObject) jObj.get("data");
            m_log.debug(data);

        } finally {
            resp.close();
        }
    } finally {
        httpClient.close();
    }
    return data;
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/*  w w w. j av a 2s .c  om*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}

From source file:com.code42.demo.RestInvoker.java

/**
 * Execuites CODE42 api/File to upload a single file into the root directory of the specified planUid
 * If the file is succesfully uploaded the response code of 204 is returned.
 * /*from  w  w w. j ava 2  s . com*/
 * @param planUid 
 * @param sessionId
 * @param file
 * @return HTTP Response code as int
 * @throws Exception
 */

public int postFileAPI(String planUid, String sessionId, File file) throws Exception {

    int respCode;
    HttpClientBuilder hcs;
    CloseableHttpClient httpClient;
    hcs = HttpClients.custom().setDefaultCredentialsProvider(credsProvider);
    if (ssl) {
        hcs.setSSLSocketFactory(sslsf);
    }
    httpClient = hcs.build();
    StringBody planId = new StringBody(planUid, ContentType.TEXT_PLAIN);
    StringBody sId = new StringBody(sessionId, ContentType.TEXT_PLAIN);

    try {
        HttpPost httpPost = new HttpPost(ePoint + "/api/File");
        FileBody fb = new FileBody(file);
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", fb).addPart("planUid", planId)
                .addPart("sessionId", sId).build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse resp = httpClient.execute(httpPost);
        try {
            m_log.info("executing " + httpPost.getRequestLine());
            m_log.info(resp.getStatusLine());
            respCode = resp.getStatusLine().getStatusCode();
        } finally {
            resp.close();
        }

    } finally {
        httpClient.close();
    }

    return respCode;
}

From source file:cloudfoundry.norouter.f5.client.HttpClientIControlClient.java

private HttpClientIControlClient(HttpHost host, Builder builder) {
    super(URI.create(host.toURI()));
    this.host = host;

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
            Objects.requireNonNull(builder.user, "user is a required argument"),
            Objects.requireNonNull(builder.password, "password is a required argument"));
    credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), credentials);

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setUserAgent("curl/7.37.1")
            .disableCookieManagement().setDefaultCredentialsProvider(credentialsProvider);
    if (builder.skipVerifyTls) {
        httpClientBuilder.setSSLSocketFactory(NaiveTrustManager.getSocketFactory());
    }//from  w  w w  .  java  2 s  .com
    httpClient = httpClientBuilder.build();
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/*from  ww  w . j a v  a  2  s. c o m*/
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java

@Override
public CloseableHttpClient createHttpClient(HttpHost httpHost, boolean acceptAnyCertificate) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    //configure proxy from system environment
    builder.setRoutePlanner(new SystemDefaultRoutePlanner(null));

    //accept any certificate if necessary
    if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) {
        SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory();
        builder.setSSLSocketFactory(icsf);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", icsf).build();
        HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry);
        builder.setConnectionManager(cm);
    }//from  w ww.  j av a2s  . com

    //add an interceptor that replaces the invalid Content-Type
    //'none' by 'identity'
    builder.addInterceptorFirst(new ContentEncodingNoneInterceptor());

    CloseableHttpClient client = builder.build();
    return client;
}

From source file:com.github.technosf.posterer.modules.commons.transport.CommonsRequestModelImpl.java

/**
 * Configures builder for the given SSL/TLS version
 * //from  ww  w.  jav  a 2s .  c om
 * @param builder
 *            the builder to configure
 * @param ssl
 *            the ssl info
 */
private @Nullable BooleanSupplier buildInSSL(Auditor auditor, HttpClientBuilder builder, final String ssl) {
    builder.setSSLHostnameVerifier(new PromiscuousHostnameVerifier(auditor));
    try {
        AuditingSSLSocketFactory auditingSSLSocketFactory = new AuditingSSLSocketFactory(auditor, ssl);
        builder.setSSLSocketFactory(auditingSSLSocketFactory);
        return auditingSSLSocketFactory.getNeededClientAuthSupplier();
    } catch (KeyManagementException | UnrecoverableKeyException e) {
        auditor.append(true, CONST_ERR_SSL_KEY).append(false, "\t%1$s", e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        auditor.append(true, CONST_ERR_SSL_ALGO).append(false, "\t%1$s", e.getMessage());
    } catch (KeyStoreException e) {
        auditor.append(true, CONST_ERR_SSL_STORE).append(false, "\t%1$s", e.getMessage());
    } catch (FileNotFoundException e) {
        auditor.append(true, CONST_ERR_SSL_FILE).append(false, "\t%1$s", e.getMessage());
    } catch (CertificateException e) {
        auditor.append(true, CONST_ERR_SSL_CERT).append(false, "\t%1$s", e.getMessage());
    } catch (IOException e) {
        auditor.append(true, CONST_ERR_SSL_IO).append(false, "\t%1$s", e.getMessage());
    }

    return null;
}

From source file:org.flowable.app.service.idm.RemoteIdmServiceImpl.java

protected JsonNode callRemoteIdmService(String url, String username, String password) {
    HttpGet httpGet = new HttpGet(url);
    httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic "
            + new String(Base64.encodeBase64((username + ":" + password).getBytes(Charset.forName("UTF-8")))));

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {//  w  w  w .  ja v  a 2 s. c  o m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.warn("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return objectMapper.readTree(response.getEntity().getContent());
        }
    } catch (Exception e) {
        logger.warn("Exception while getting token", e);
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
    return null;
}