org.apache.http.client.AuthCache

Here are the examples of the java api class org.apache.http.client.AuthCache taken from open source projects.

1. WireMockTestClient#getWithPreemptiveCredentials()

Project: wiremock
File: WireMockTestClient.java
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    HttpHost target = new HttpHost("localhost", port);
    HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}

2. BasicAuthTest#createAuthenticatingExecutor()

Project: Resteasy
File: BasicAuthTest.java
/**
    * Create a ClientExecutor which does preemptive authentication.
    */
private static ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost("localhost", 8081);
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Create ClientExecutor.
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
    return executor;
}

3. TestSecureLinks#before()

Project: Resteasy
File: TestSecureLinks.java
@Before
public void before() {
    POJOResourceFactory noDefaults = new POJOResourceFactory(resourceType);
    dispatcher.getRegistry().addResourceFactory(noDefaults);
    url = generateBaseUrl();
    // Configure HttpClient to authenticate preemptively
    // by prepopulating the authentication data cache.
    // 1. Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // 2. Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(getHttpHost(url), basicAuth);
    // 3. Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    httpClient = new DefaultHttpClient();
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext);
    client = ProxyFactory.create(BookStoreService.class, url, executor);
}

4. BasicAuthTest#createAuthenticatingExecutor()

Project: Resteasy
File: BasicAuthTest.java
/**
    * Create a ClientExecutor which does preemptive authentication.
    */
private static ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost("localhost", 8081);
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Create ClientExecutor.
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
    return executor;
}

5. BasicAuthTest#createAuthenticatingEngine()

Project: Resteasy
File: BasicAuthTest.java
private static ClientHttpEngine createAuthenticatingEngine(DefaultHttpClient client) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost("localhost", 8081);
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Create ClientHttpEngine
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(client, localContext);
    return engine;
}

6. BasicAuthTest#createAuthenticatingExecutor()

Project: Resteasy
File: BasicAuthTest.java
/**
    * Create a ClientExecutor which does preemptive authentication.
    */
private static ClientExecutor createAuthenticatingExecutor(DefaultHttpClient client) {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost("localhost", 8081);
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Create ClientExecutor.
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);
    return executor;
}

7. HDInsightInstance#getClientContext()

Project: reef
File: HDInsightInstance.java
private HttpClientContext getClientContext(final String hostname, final String username, final String password) throws IOException {
    final HttpHost targetHost = new HttpHost(hostname, 443, "https");
    final HttpClientContext result = HttpClientContext.create();
    // Setup credentials provider
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    result.setCredentialsProvider(credentialsProvider);
    // Setup preemptive authentication
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    result.setAuthCache(authCache);
    final HttpGet httpget = new HttpGet("/");
    // Prime the cache
    try (final CloseableHttpResponse response = this.httpClient.execute(targetHost, httpget, result)) {
    // empty try block used to automatically close resources
    }
    return result;
}

8. AvroSchemaSource#initHttpRestClient()

Project: kaa
File: AvroSchemaSource.java
private void initHttpRestClient() {
    httpClient = new DefaultHttpClient();
    restHost = new HttpHost(kaaRestHost, kaaRestPort, "http");
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(restHost, basicAuth);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(kaaRestHost, kaaRestPort, AuthScope.ANY_REALM), new UsernamePasswordCredentials(kaaRestUser, kaaRestPassword));
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
}

9. PreemptiveBasicAuthenticator#apply()

Project: jena
File: PreemptiveBasicAuthenticator.java
@Override
public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) {
    this.authenticator.apply(client, httpContext, target);
    // Enable preemptive basic authentication
    // For nice layering we need to respect existing auth cache if present
    AuthCache authCache = (AuthCache) httpContext.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null)
        authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(this.isProxy ? ChallengeState.PROXY : ChallengeState.TARGET);
    // TODO It is possible that this overwrites existing cached credentials
    // so potentially not ideal.
    authCache.put(new HttpHost(target.getHost(), target.getPort()), basicAuth);
    httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

10. AuthenticatedAccessTest#getClientWithServerAdminCredentials()

Project: hibernate-ogm
File: AuthenticatedAccessTest.java
private static ResteasyClient getClientWithServerAdminCredentials() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(serverAdminUser, serverAdminPassword));
    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(host, port, "http"), new BasicScheme());
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient, localContext)).build();
}

11. ConfluenceUserImageProvider#getRequestContext()

Project: communote-server
File: ConfluenceUserImageProvider.java
@Override
protected HttpContext getRequestContext(URI imageUrl, String imageIdentifier, ConfluenceConfiguration config) {
    HttpHost targetHost = new HttpHost(imageUrl.getHost(), imageUrl.getPort());
    CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
    credentialsProviderProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(config.getAdminLogin(), config.getAdminPassword()));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    // preemptive authentication (send credentials with request) by adding host to auth cache
    // TODO maybe use real basic auth challenge?
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProviderProvider);
    context.setAuthCache(authCache);
    return context;
}

12. JestHttpClientTest#createContextInstanceWithPreemptiveAuth()

Project: Jest
File: JestHttpClientTest.java
@Test
public void createContextInstanceWithPreemptiveAuth() {
    AuthCache authCacheMock = mock(AuthCache.class);
    CredentialsProvider credentialsProviderMock = mock(CredentialsProvider.class);
    HttpClientContext httpClientContextTemplate = HttpClientContext.create();
    httpClientContextTemplate.setAuthCache(authCacheMock);
    httpClientContextTemplate.setCredentialsProvider(credentialsProviderMock);
    JestHttpClient jestHttpClient = (JestHttpClient) new JestClientFactory().getObject();
    jestHttpClient.setHttpClientContextTemplate(httpClientContextTemplate);
    HttpClientContext httpClientContextResult = jestHttpClient.createContextInstance();
    assertEquals(authCacheMock, httpClientContextResult.getAuthCache());
    assertEquals(credentialsProviderMock, httpClientContextResult.getCredentialsProvider());
}

13. DownloadAction#addAuthentication()

Project: gradle-download-task
File: DownloadAction.java
/**
     * Add authentication information for the given host
     * @param host the host
     * @param username the username
     * @param password the password
     * @param preAuthenticate <code>true</code> if the authentication scheme
     * should be set to <code>Basic</code> preemptively (should be
     * <code>false</code> if adding authentication for a proxy server)
     * @param context the context in which the authentication information
     * should be saved
     */
private void addAuthentication(HttpHost host, String username, String password, boolean preAuthenticate, HttpClientContext context) {
    AuthCache authCache = context.getAuthCache();
    if (authCache == null) {
        authCache = new BasicAuthCache();
        context.setAuthCache(authCache);
    }
    CredentialsProvider credsProvider = context.getCredentialsProvider();
    if (credsProvider == null) {
        credsProvider = new BasicCredentialsProvider();
        context.setCredentialsProvider(credsProvider);
    }
    credsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(username, password));
    if (preAuthenticate) {
        authCache.put(host, new BasicScheme());
    }
}

14. RDFGeneratorServlet#invokeHTTPDeleteWithAuth()

Project: Web-Karma
File: RDFGeneratorServlet.java
private int invokeHTTPDeleteWithAuth(HttpHost httpHost, String url, String userName, String password) throws ClientProtocolException, IOException {
    HttpDelete httpDelete = new HttpDelete(url);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(userName, password));
    AuthCache authCache = new BasicAuthCache();
    DigestScheme digestScheme = new DigestScheme();
    // Virtuoso specific
    digestScheme.overrideParamter("realm", "SPARQL");
    // digestScheme.overrideParamter("nonce", new Nonc);
    authCache.put(httpHost, digestScheme);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Execute the request
    HttpResponse response = httpClient.execute(httpHost, httpDelete, localcontext);
    logger.info(Integer.toString(response.getStatusLine().getStatusCode()));
    return response.getStatusLine().getStatusCode();
}

15. RDFGeneratorServlet#invokeHTTPRequestWithAuth()

Project: Web-Karma
File: RDFGeneratorServlet.java
private int invokeHTTPRequestWithAuth(HttpHost httpHost, HttpPost httpPost, String contentType, String acceptContentType, String userName, String password) throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (acceptContentType != null && !acceptContentType.isEmpty()) {
        httpPost.setHeader(HTTP_HEADERS.Accept.name(), acceptContentType);
    }
    if (contentType != null && !contentType.isEmpty()) {
        httpPost.setHeader("Content-Type", contentType);
    }
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(userName, password));
    AuthCache authCache = new BasicAuthCache();
    DigestScheme digestScheme = new DigestScheme();
    // Virtuoso specific
    digestScheme.overrideParamter("realm", "SPARQL");
    // digestScheme.overrideParamter("nonce", new Nonc);
    authCache.put(httpHost, digestScheme);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Execute the request
    HttpResponse response = httpClient.execute(httpHost, httpPost, localcontext);
    return response.getStatusLine().getStatusCode();
}

16. HttpUtils#setAuth()

Project: syncope
File: HttpUtils.java
private HttpClientContext setAuth(final HttpHost targetHost, final AuthScheme authScheme) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password));
    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, authScheme);
    context.setAuthCache(authCache);
    context.setCredentialsProvider(credsProvider);
    return context;
}

17. HttpHelper#buildClientContext()

Project: sputnik
File: HttpHelper.java
@NotNull
public HttpClientContext buildClientContext(@NotNull HttpHost httpHost, @NotNull AuthScheme authScheme) {
    AuthCache basicAuthCache = new BasicAuthCache();
    basicAuthCache.put(httpHost, authScheme);
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setAuthCache(basicAuthCache);
    httpClientContext.setTargetHost(httpHost);
    return httpClientContext;
}

18. BaseHttpTest#exec()

Project: orientdb
File: BaseHttpTest.java
protected BaseHttpTest exec() throws IOException {
    final HttpHost targetHost = new HttpHost(getHost(), getPort(), getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(getUserName(), getUserPassword()));
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    if (keepAlive != null)
        request.addHeader("Connection", keepAlive ? "Keep-Alive" : "Close");
    if (payload != null && request instanceof HttpEntityEnclosingRequestBase)
        ((HttpEntityEnclosingRequestBase) request).setEntity(payload);
    final CloseableHttpClient httpClient = HttpClients.createDefault();
    //    DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(retry, false);
    //    context.setAttribute(HttpMethodParams.RETRY_HANDLER, retryhandler);
    response = httpClient.execute(targetHost, request, context);
    return this;
}

19. Tr064Comm#createTr064HttpClient()

Project: openhab
File: Tr064Comm.java
/***
     * Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
     * and sets Auth. Scheme to Digest Auth
     *
     * @param fboxUrl the URL from config file of fbox to connect to
     * @return the ready-to-use httpclient for tr064 requests
     */
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);
    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
    // auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    // known from fbox specification
    digestAuth.overrideParamter("realm", "HTTPS Access");
    // never known at first request
    digestAuth.overrideParamter("nonce", "");
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);
    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        // accept self signed certs
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        // dont
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
    // verify
    // hostname
    // against
    // cert
    // CN
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }
    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
    // BUILDER
    // setup builder with parameters defined before
    hc = // set the SSL options which trust every self signed
    HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// cert
    credp).setDefaultRequestConfig(// set auth options using digest
    rc).build();
    return hc;
}

20. JiraSession#getRest()

Project: manifoldcf
File: JiraSession.java
private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside);
    method.addHeader("Accept", "application/json");
    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);
        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode != 200)
            throw new IOException("Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        Object jo = convertToJSON(httpResponse);
        response.acceptJSONObject(jo);
    } finally {
        method.abort();
    }
}

21. JiraSession#getRest()

Project: manifoldcf
File: JiraSession.java
private void getRest(String rightside, JiraJSONResponse response) throws IOException, ResponseException {
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    final HttpRequestBase method = new HttpGet(host.toURI() + path + rightside);
    method.addHeader("Accept", "application/json");
    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);
        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode != 200)
            throw new ResponseException("Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        Object jo = convertToJSON(httpResponse);
        response.acceptJSONObject(jo);
    } finally {
        method.abort();
    }
}

22. CouchDBUtils#getContext()

Project: Kundera
File: CouchDBUtils.java
/**
     * Gets the context.
     * 
     * @param httpHost
     *            the http host
     * @return the context
     */
public static HttpContext getContext(HttpHost httpHost) {
    AuthCache authCache = new BasicAuthCache();
    authCache.put(httpHost, new BasicScheme());
    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return context;
}

23. HttpComponentsRequestFactoryBasicAuth#createHttpContext()

Project: kaa
File: HttpComponentsRequestFactoryBasicAuth.java
private HttpContext createHttpContext() {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

24. JestClientFactory#createBasicAuthCache()

Project: Jest
File: JestClientFactory.java
private AuthCache createBasicAuthCache(HttpHost targetHost) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    return authCache;
}

25. ApiTokenPropertyTest#configureWebConnection()

Project: Jenkins2
File: ApiTokenPropertyTest.java
private void configureWebConnection(final WebClient wc, final String username, final String token) throws IOException {
    // See https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    final UsernamePasswordCredentials fooCreds = new UsernamePasswordCredentials(username, token);
    URL hostUrl = j.getURL();
    final HttpHost targetHost = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), hostUrl.getProtocol());
    CredentialsProvider credsProvider = new BasicCredentialsProvider() {

        @Override
        public Credentials getCredentials(AuthScope authscope) {
            return fooCreds;
        }
    };
    credsProvider.setCredentials(new AuthScope("localhost", AuthScope.ANY_PORT, AuthScope.ANY_REALM), fooCreds);
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    AuthScheme authScheme = new BasicScheme();
    authCache.put(targetHost, authScheme);
    // Add AuthCache to the execution context
    final HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    wc.setCredentialsProvider(credsProvider);
    // Need to create our own WebConnection that gives us control of HttpClient execution,
    // allowing us to pass our own HttpClientContext etc. HttpWebConnection has its own
    // private HttpClientContext instance, which means we can't authenticate properly.
    wc.setWebConnection(new WebConnection() {

        @Override
        public WebResponse getResponse(WebRequest request) throws IOException {
            try {
                long startTime = System.currentTimeMillis();
                HttpClientBuilder builder = HttpClientBuilder.create();
                CloseableHttpClient httpClient = builder.build();
                URL url = UrlUtils.encodeUrl(request.getUrl(), false, request.getCharset());
                HttpGet method = new HttpGet(url.toURI());
                CloseableHttpResponse response = httpClient.execute(targetHost, method, context);
                HttpEntity httpEntity = response.getEntity();
                DownloadedContent responseBody = HttpWebConnection.downloadContent(httpEntity.getContent(), wc.getOptions().getMaxInMemory());
                String statusMessage = response.getStatusLine().getReasonPhrase();
                if (statusMessage == null) {
                    statusMessage = "Unknown status message";
                }
                int statusCode = response.getStatusLine().getStatusCode();
                List<NameValuePair> headers = new ArrayList<>();
                for (final Header header : response.getAllHeaders()) {
                    headers.add(new NameValuePair(header.getName(), header.getValue()));
                }
                WebResponseData responseData = new WebResponseData(responseBody, statusCode, statusMessage, headers);
                return new WebResponse(responseData, request, (System.currentTimeMillis() - startTime));
            } catch (Exception e) {
                throw new AssertionError("Failed to execute WebRequest.", e);
            }
        }
    });
}

26. WorkingCopyWebdavClient#getResourceUsingHttpclient()

Project: continuum
File: WorkingCopyWebdavClient.java
private static void getResourceUsingHttpclient(String resourceUrl, String username, String password) throws URISyntaxException, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    URL url = new URL(resourceUrl);
    URI uri = url.toURI();
    HttpGet httpGet = new HttpGet(uri);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    System.out.println("Retrieving resource '" + url.toString() + "' using HttpClient's get method..");
    HttpResponse httpResponse = httpClient.execute(targetHost, httpGet, localcontext);
    System.out.println("Response status code :: " + httpResponse.getStatusLine().getStatusCode());
    InputStream is = IOUtils.toInputStream(EntityUtils.toString(httpResponse.getEntity(), EntityUtils.getContentCharSet(httpResponse.getEntity())));
    String content = IOUtils.toString(is);
    System.out.println("Content :: " + content);
}