public CloseableHttpClient getHttpClient ( ) { try { URI crxUri = new URI ( props . getPackageManagerUrl ( ) ) ; final AuthScope authScope = new AuthScope ( crxUri . getHost ( ) , crxUri . getPort ( ) ) ; final Credentials credentials = new UsernamePasswordCredentials ( props . getUserId ( ) , props . getPassword ( ) ) ; final CredentialsProvider credsProvider = new BasicCredentialsProvider ( ) ; credsProvider . setCredentials ( authScope , credentials ) ; HttpClientBuilder httpClientBuilder = HttpClients . custom ( ) . setDefaultCredentialsProvider ( credsProvider ) . addInterceptorFirst ( new HttpRequestInterceptor ( ) { @ Override public void process ( HttpRequest request , HttpContext context ) throws HttpException , IOException { // enable preemptive authentication AuthState authState = ( AuthState ) context . getAttribute ( HttpClientContext . TARGET_AUTH_STATE ) ; authState . update ( new BasicScheme ( ) , credentials ) ; } } ) . setKeepAliveStrategy ( new ConnectionKeepAliveStrategy ( ) { @ Override public long getKeepAliveDuration ( HttpResponse response , HttpContext context ) { // keep reusing connections to a minimum - may conflict when instance is restarting and responds in unexpected manner return 1 ; } } ) ; // timeout settings httpClientBuilder . setDefaultRequestConfig ( HttpClientUtil . buildRequestConfig ( props ) ) ; // relaxed SSL check if ( props . isRelaxedSSLCheck ( ) ) { SSLContext sslContext = new SSLContextBuilder ( ) . loadTrustMaterial ( null , new TrustSelfSignedStrategy ( ) ) . build ( ) ; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory ( sslContext , new NoopHostnameVerifier ( ) ) ; httpClientBuilder . setSSLSocketFactory ( sslsf ) ; } // proxy support Proxy proxy = getProxyForUrl ( props . getPackageManagerUrl ( ) ) ; if ( proxy != null ) { httpClientBuilder . setProxy ( new HttpHost ( proxy . getHost ( ) , proxy . getPort ( ) , proxy . getProtocol ( ) ) ) ; if ( proxy . useAuthentication ( ) ) { AuthScope proxyAuthScope = new AuthScope ( proxy . getHost ( ) , proxy . getPort ( ) ) ; Credentials proxyCredentials = new UsernamePasswordCredentials ( proxy . getUsername ( ) , proxy . getPassword ( ) ) ; credsProvider . setCredentials ( proxyAuthScope , proxyCredentials ) ; } } return httpClientBuilder . build ( ) ; } catch ( URISyntaxException ex ) { throw new PackageManagerException ( "Invalid url: " + props . getPackageManagerUrl ( ) , ex ) ; } catch ( KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex ) { throw new PackageManagerException ( "Could not set relaxedSSLCheck" , ex ) ; } }
Set up http client with credentials