Java Code Examples for org.apache.http.impl.client.HttpClientBuilder#setSslcontext()

The following examples show how to use org.apache.http.impl.client.HttpClientBuilder#setSslcontext() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RabbitMQHttpClient.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username, final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory, final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create().
            setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}
 
Example 2
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void setupClient() {
    final HttpClientBuilder clientBuilder = HttpClients.custom();

    if (sslContext != null) {
        clientBuilder.setSslcontext(sslContext);
        clientBuilder.addInterceptorFirst(new HttpsResponseInterceptor());
    }

    httpClient = clientBuilder
        .setDefaultCredentialsProvider(getCredentialsProvider()).build();
}
 
Example 3
Source File: RestUtil.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
                                                     .useSystemProperties();

    if (trustSelfSignedCerts) {
        httpClientBuilder.setSslcontext(buildSslContext());
        httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }

    if (httpProxyConfiguration != null) {
        HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
        httpClientBuilder.setProxy(proxy);

        if (httpProxyConfiguration.isAuthRequired()) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(httpProxyConfiguration.getProxyHost(),
                                                             httpProxyConfiguration.getProxyPort()),
                                               new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
                                                                               httpProxyConfiguration.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }

    HttpClient httpClient = httpClientBuilder.build();

    return new HttpComponentsClientHttpRequestFactory(httpClient);
}
 
Example 4
Source File: FakeAOSmithWaterHeater.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private void pollServer() {	   
   Timer oldTimer = timerRef.getAndSet(null);
   if (oldTimer != null) {
      oldTimer.cancel();
   }
   HttpClientBuilder builder = HttpClientBuilder.create();
   builder.setSslcontext(sslContext);
	CloseableHttpClient httpClient = builder.build();
	
	boolean fastPoll = false;
	try {
		StringEntity entity = new StringEntity(buildPayload(), ContentType.APPLICATION_FORM_URLENCODED);
		HttpUriRequest pollingMsg = RequestBuilder.post()
				.setUri(uri)
				.setEntity(entity)
				.build();
		CloseableHttpResponse response = httpClient.execute(pollingMsg);
		try {
			HttpEntity stuff = response.getEntity();
			String thing = EntityUtils.toString(stuff);
			System.out.println("####\n#### RESPONSE " + response.getStatusLine());
			System.out.println("####\n    Response Message: " + thing + "\n####");
			
			fastPoll = applyResults(thing);
		}
		finally {
			response.close();
		}
	}
	catch(Exception ex) {
		ex.printStackTrace();
	}
	finally {
		try {
			httpClient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   timerRef.set(new Timer());
		if (fastPoll) {
		   System.out.println("####\n#### Schedule Fast Poll: " + FAST_POLL + "s" + "\n####");
		   timerRef.get().schedule(new PollServerTask(), FAST_POLL * 1000);
		}
		else {
		   int pollingInterval = Integer.valueOf(state.get(AosConstants.AOS_PARAM_UPDATERATE));
		   System.out.println("####\n#### Schedule Standard Poll: " + pollingInterval + "s" + "\n####");
		   timerRef.get().schedule(new PollServerTask(), pollingInterval * 1000);
		}
	}
}
 
Example 5
Source File: WebUtil.java    From dal with Apache License 2.0 4 votes vote down vote up
private static HttpClient initWeakSSLClient() {
    HttpClientBuilder b = HttpClientBuilder.create();
    // setup a Trust Strategy that allows all certificates.
    //
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        // do nothing, has been handled outside
    }
    b.setSslcontext(sslContext);

    // don't check Hostnames, either.
    // -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
    X509HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    // here's the special part:
    // -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    // -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory)
            .build();

    // now, we create connection-manager using our Registry.
    // -- allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    /**
     * Set timeout option
     */
    RequestConfig.Builder configBuilder = RequestConfig.custom();
    configBuilder.setConnectTimeout(TIMEOUT);
    configBuilder.setSocketTimeout(TIMEOUT);
    b.setDefaultRequestConfig(configBuilder.build());

    // finally, build the HttpClient;
    // -- done!
    HttpClient sslClient = b.build();
    return sslClient;
}
 
Example 6
Source File: ApacheGatewayConnection.java    From vespa with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
private static void setSslContext(HttpClientBuilder builder, SSLContext sslContext) {
    builder.setSslcontext(sslContext);
}