Java 类org.apache.http.impl.client.BasicAuthCache 实例源码

项目:purecloud-iot    文件:TestClientAuthentication.java   
@Test
public void testPreemptiveAuthentication() throws Exception {
    final CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.serverBootstrap.registerHandler("*", requestHandler);

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());
    context.setAuthCache(authCache);
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("test", "test"));
    context.setCredentialsProvider(credsProvider);

    final HttpGet httpget = new HttpGet("/");
    final HttpResponse response1 = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
}
项目:nextcloud-java-api    文件:ConnectorCommon.java   
private HttpClientContext prepareContext()
{
    HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
项目:living-documentation    文件:ConfluenceRestClient.java   
private HttpContext httpContext() {
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    if (isNotBlank(this.username) && this.password != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        HttpHost httpHost = HttpHost.create(this.rootConfluenceUrl);
        AuthScope authScope = new AuthScope(httpHost);
        basicCredentialsProvider.setCredentials(authScope, credentials);

        BasicAuthCache basicAuthCache = new BasicAuthCache();
        basicAuthCache.put(httpHost, new BasicScheme());

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(basicCredentialsProvider);
        httpClientContext.setAuthCache(basicAuthCache);

        return httpClientContext;
    } else {
        return null;
    }
}
项目:aws-sdk-java-v2    文件:ApacheUtils.java   
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.endpoint().getHost(), proxyConfiguration.endpoint().getPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
项目:ibm-cos-sdk-java    文件:ApacheUtils.java   
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
项目:geoportal-server-harvester    文件:HttpClientContextBuilder.java   
/**
 * Creates client context.
 * @param url url
 * @param cred credentials
 * @return client context
 */
public static HttpClientContext createHttpClientContext(URL url, SimpleCredentials cred) {
  HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
          new UsernamePasswordCredentials(cred.getUserName(),cred.getPassword()));    

  // 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);

  return context;
}
项目:BitcoindConnector4J    文件:BitcoindApiHandler.java   
public BitcoindApiHandler(String host, int port, String protocol, String uri, String username, String password) {
    this.uri = uri;

    httpClient = HttpClients.createDefault();

    targetHost = new HttpHost(host, port, protocol);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
}
项目:eSDK_EC_SDK_Java    文件:RestfulAdapterImplHttpClient.java   
private synchronized void checkLocalContext()
{
    if (null != sdkProtocolAdatperCustProvider && null != target)
    {
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local auth cache
        String authType = (String) ThreadLocalHolder.get().getEntities().get("AuthType");
        if ("Basic".equals(authType))
        {
            LOGGER.debug("authentication type: basic");
        }
        else
        {
            DigestScheme digestAuth = new DigestScheme();
            digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++));
            digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", ""));
            digestAuth.overrideParamter("qop", "auth");
            authCache.put(target, digestAuth);
        }

        // Add AuthCache to the execution context
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}
项目:eSDK_EC_SDK_Java    文件:RestfulAdapterImplHttpClientHTLS.java   
private synchronized void checkLocalContext()
{
    if (null != sdkProtocolAdatperCustProvider && null != target)
    {
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local auth cache
        String authType = (String)ThreadLocalHolder.get().getEntities().get("AuthType");
        if ("Basic".equals(authType))
        {
            LOGGER.debug("authentication type: basic");
        }
        else
        {
            DigestScheme digestAuth = new DigestScheme();
            digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++));
            digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", ""));
            digestAuth.overrideParamter("qop", "auth");
            authCache.put(target, digestAuth);
        }

        // Add AuthCache to the execution context
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}
项目:infiniboard    文件:UrlSourceJob.java   
private HttpClientContext configureContext(CredentialsProvider credentialsProvider, String url) {
  if (credentialsProvider != null) {
    try {
      URL targetUrl = new URL(url);

      HttpHost targetHost =
          new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
      AuthCache authCache = new BasicAuthCache();
      authCache.put(targetHost, new BasicScheme());

      final HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(credentialsProvider);
      context.setAuthCache(authCache);

      return context;
    } catch (MalformedURLException e) {
      LOG.error("Cannot parse URL '{}'", url, e);
    }
  }
  return null;
}
项目:eSDK_IVS_Java    文件:RestfulAdapterImplHttpClient.java   
private synchronized void checkLocalContext()
{
    if (null != sdkProtocolAdatperCustProvider && null != target)
    {
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local auth cache
        String authType = (String) ThreadLocalHolder.get().getEntities().get("AuthType");
        if ("Basic".equals(authType))
        {
            LOGGER.debug("authentication type: basic");
        }
        else
        {
            DigestScheme digestAuth = new DigestScheme();
            digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++));
            digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", ""));
            digestAuth.overrideParamter("qop", "auth");
            authCache.put(target, digestAuth);
        }

        // Add AuthCache to the execution context
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}
项目:eSDK_IVS_Java    文件:RestfulAdapterImplHttpClientHTLS.java   
private synchronized void checkLocalContext()
{
    if (null != sdkProtocolAdatperCustProvider && null != target)
    {
        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate DIGEST scheme object, initialize it and add it to the local auth cache
        String authType = (String)ThreadLocalHolder.get().getEntities().get("AuthType");
        if ("Basic".equals(authType))
        {
            LOGGER.debug("authentication type: basic");
        }
        else
        {
            DigestScheme digestAuth = new DigestScheme();
            digestAuth.overrideParamter("nc", String.valueOf(serverNounceCount++));
            digestAuth.overrideParamter("cnonce", UUID.randomUUID().toString().replaceAll("-", ""));
            digestAuth.overrideParamter("qop", "auth");
            authCache.put(target, digestAuth);
        }

        // Add AuthCache to the execution context
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}
项目:java-triton    文件:CloudApiApacheHttpClientContext.java   
/**
 * Builds a configured HTTP context object that is pre-configured for
 * using HTTP Signature authentication.
 *
 * @param configurator HTTP Signatures configuration helper to pull properties from
 * @return configured HTTP context object
 */
protected HttpContext buildHttpContext(final HttpSignatureConfigurator configurator) {
    final HttpClientContext context = HttpClientContext.create();

    if (configurator != null) {
        AuthCache authCache = new BasicAuthCache();
        context.setAuthCache(authCache);

        AuthState authState = new AuthState();
        authState.update(configurator.getAuthScheme(), configurator.getCredentials());

        context.setAttribute(HttpClientContext.TARGET_AUTH_STATE,
                authState);
        context.getTargetAuthState().setState(AuthProtocolState.UNCHALLENGED);

    }

    return context;
}
项目:ibm-bpm-rest-client    文件:SimpleBpmClient.java   
private CloseableHttpClient createClient(String user, String password) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(TOTAL_CONN);
    cm.setDefaultMaxPerRoute(ROUTE_CONN);

    logger.info("Pooling connection manager created.");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    logger.info("Default credentials provider created.");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicAuth);
    logger.info("Auth cache created.");

    httpContext = HttpClientContext.create();
    httpContext.setCredentialsProvider(credentialsProvider);
    httpContext.setAuthCache(authCache);
    logger.info("HttpContext filled with Auth cache.");

    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm)
            .build();
}
项目:boteco    文件:DefaultRestConfiguration.java   
@Override
public RestConfiguration withAuthentication(String user, String password) {
  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();
  // Generate BASIC scheme object and add it to the local auth cache
  BasicScheme basicAuth = new BasicScheme();
  CredentialsProvider provider = new BasicCredentialsProvider();

  URI uri = request.getURI();
  authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
  provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
      new UsernamePasswordCredentials(user, password));

  this.context.setCredentialsProvider(provider);
  this.context.setAuthCache(authCache);

  return this;
}
项目:communote-server    文件: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;
}
项目:playground    文件:BasicAuthConfigurator.java   
@Override
    public BasicHttpContext createContext(HttpHost targetHost) {

        final AuthCache authCache = new BasicAuthCache();

        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // OPTIMIZED
        credentialsProvider
                .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        // NON-OPTIMIZED
//        credentialsProvider.setCredentials(
//                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
//                new UsernamePasswordCredentials(username, password));

        final BasicHttpContext context = new BasicHttpContext();
        context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        context.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);

        return context;
    }
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testPreemptiveTargetAndProxyAuth() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNotNull(this.targetState.getAuthScheme());
    Assert.assertSame(this.creds1, this.targetState.getCredentials());
    Assert.assertNotNull(this.proxyState.getAuthScheme());
    Assert.assertSame(this.creds2, this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testCredentialsProviderNotSet() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, null);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testAuthCacheEmpty() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Test
public void testNoMatchingCredentials() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");

    this.credProvider.clear();

    final HttpClientContext context = HttpClientContext.create();
    context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credProvider);
    context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.target);
    context.setAttribute(HttpClientContext.HTTP_ROUTE, new HttpRoute(this.target, null, this.proxy, false));
    context.setAttribute(HttpClientContext.TARGET_AUTH_STATE, this.targetState);
    context.setAttribute(HttpClientContext.PROXY_AUTH_STATE, this.proxyState);

    final AuthCache authCache = new BasicAuthCache();
    authCache.put(this.target, this.authscheme1);
    authCache.put(this.proxy, this.authscheme2);

    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

    final HttpRequestInterceptor interceptor = new RequestAuthCache();
    interceptor.process(request, context);
    Assert.assertNull(this.targetState.getAuthScheme());
    Assert.assertNull(this.targetState.getCredentials());
    Assert.assertNull(this.proxyState.getAuthScheme());
    Assert.assertNull(this.proxyState.getCredentials());
}
项目:purecloud-iot    文件:TestClientAuthentication.java   
@Test
public void testPreemptiveAuthenticationFailure() throws Exception {
    final CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.serverBootstrap.registerHandler("*", requestHandler);

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());
    context.setAuthCache(authCache);
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("test", "stuff"));
    context.setCredentialsProvider(credsProvider);

    final HttpGet httpget = new HttpGet("/");
    final HttpResponse response1 = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
}
项目:Cytomine-client-autobuilder    文件:HttpClient.java   
public void connect(String url, String username, String password) throws Exception {
    isAuthByPrivateKey = false;
    log.info("Connection to " + url + " with login=" + username + " and pass=" + password);
    URL = new URL(url);
    targetHost = new HttpHost(URL.getHost(), URL.getPort());
    client = new DefaultHttpClient();
    // 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
    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
}
项目:zee-jenkins    文件:RestClient.java   
private HttpClientContext createClientContext(
        String hostAddressWithProtocol, String userName, String password) {
    URL url;
    try {
        url = new URL(hostAddressWithProtocol);
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(),
                url.getProtocol());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());

        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return context;
}
项目:majordodo    文件:HTTPClientConnection.java   
private HttpClientContext getContext() throws IOException {
    if (context == null) {
        BrokerAddress broker = getBroker();
        String scheme = broker.getProtocol();
        HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme);

        context = HttpClientContext.create();
        if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                creds);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }

    }
    return context;
}
项目:dss    文件:CommonsDataLoader.java   
protected HttpResponse getHttpResponse(final CloseableHttpClient client, final HttpUriRequest httpRequest, final String url) throws DSSException {

        final String host = httpRequest.getURI().getHost();
        final int port = httpRequest.getURI().getPort();
        final String scheme = httpRequest.getURI().getScheme();
        final HttpHost targetHost = new HttpHost(host, port, scheme);

        // 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 localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        try {
            final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
            return response;
        } catch (IOException e) {
            throw new DSSException(e);
        }

    }
项目:zfj-jenkins    文件:RestClient.java   
private HttpClientContext createClientContext(
        String hostAddressWithProtocol, String userName, String password) {
    URL url;
    try {
        url = new URL(hostAddressWithProtocol);
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(),
                url.getProtocol());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());

        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return context;
}
项目:slack4gerrit    文件:HttpHelper.java   
public static String getFromHttp(URL url, String user, String password) throws IOException
{
    HttpClientContext context = HttpClientContext.create();
    if (user != null)
    {

        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    }
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url.toExternalForm());
    HttpResponse response = client.execute(request, context);
    InputStreamReader streamReader = new InputStreamReader(response.getEntity().getContent());
    String data = CharStreams.toString(streamReader);
    streamReader.close();
    return data;

}
项目:wiremock-velocity-transformer    文件: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);
    }
}
项目:Lucee4    文件:HTTPEngine4Impl.java   
public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,String password, boolean preAuth) {
       // set Username and Password
       if(!StringUtil.isEmpty(username,true)) {
           if(password==null)password="";
           CredentialsProvider cp = client.getCredentialsProvider();
           cp.setCredentials(
               new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
               new UsernamePasswordCredentials(username,password));



           BasicHttpContext httpContext = new BasicHttpContext();
           if(preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
           }
           return httpContext;
       }
       return null;
}
项目:Lucee4    文件:HTTPEngineImpl.java   
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username,String password, boolean preAuth) {
       // set Username and Password
       if(!StringUtil.isEmpty(username,true)) {
           if(password==null)password="";
           CredentialsProvider cp = new BasicCredentialsProvider();
           builder.setDefaultCredentialsProvider(cp);

           cp.setCredentials(
               new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
               new UsernamePasswordCredentials(username,password));



           BasicHttpContext httpContext = new BasicHttpContext();
           if(preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
           }
           return httpContext;
       }
       return null;
}
项目:elderberry    文件:TaxiiConnection.java   
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    return context;
}
项目:PP-UnifiedViews-Plugins    文件:ConceptExtractor.java   
/**
 * Create an HTTP state after authentication with credentials for future requests
 * @return a class wrapping HTTP host, client and context used for future requests
 */
private HttpStateWrapper createHttpStateWithAuth() {
    HttpHost host = new HttpHost(config.getHost(), Integer.parseInt(config.getPort()), "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(host.getHostName(), host.getPort()),
            new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    return new HttpStateWrapper(host, httpclient, localContext);
}
项目:metron    文件:TaxiiHandler.java   
private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
  HttpClientContext context = null;
  HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
  if (username != null && password != null) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope(target.getHostName(), target.getPort()),
        new UsernamePasswordCredentials(username, password));

    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
  } else {
    context = null;
  }
  return context;
}
项目:FritzTR064    文件:FritzConnection.java   
public void init() throws ClientProtocolException, IOException, JAXBException {
    if (user != null && pwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pwd));
        AuthCache authCache = new BasicAuthCache();
        DigestScheme digestScheme = new DigestScheme();
        digestScheme.overrideParamter("realm", "F!Box SOAP-Auth");
        digestScheme.overrideParamter("nonce", Long.toString(new Random().nextLong(), 36));
        digestScheme.overrideParamter("qop", "auth");
        digestScheme.overrideParamter("nc", "0");
        digestScheme.overrideParamter("cnonce", DigestScheme.createCnonce());
        authCache.put(targetHost, digestScheme);
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
        readTR64();
    } else {
        readIGDDESC();
    }

}
项目:contest-votesapp    文件:AuthHttpComponentsClientHttpRequestFactory.java   
@Override
protected HttpContext createHttpContext(final HttpMethod httpMethod, final URI uri) {
    // Create AuthCache instance
    final AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);

    // Add AuthCache to the execution context
    final HttpClientContext localcontext = HttpClientContext.create();
    localcontext.setAuthCache(authCache);

    if (userName != null) {
        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(userName, password));
        localcontext.setCredentialsProvider(credsProvider);
    }
    return localcontext;
}
项目:hql-builder    文件:HqlWebServiceClientFactory.java   
@SuppressWarnings("deprecation")
protected org.jboss.resteasy.client.ClientExecutor setupClientExecutor() {
    AuthCache authCache = new BasicAuthCache();
    AuthScheme basicAuth = new BasicScheme();
    authCache.put(new HttpHost(getServiceUrl()), basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(URI.create(getServiceUrl()).getHost(), authCache);

    // BasicCredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();
    // Credentials credentials = new
    // UsernamePasswordCredentials("hqlbuilder", "hqlbuilder");
    // credentialsProvider.setCredentials(new
    // AuthScope(URI.create(getServiceUrl()).getHost(),
    // URI.create(getServiceUrl()).getPort()),
    // credentials);

    HttpClient httpClient = HttpClientBuilder.create()//
            // .setDefaultCredentialsProvider(credentialsProvider)//
            .build();//

    return new ApacheHttpClient4Executor(httpClient, localContext);
}
项目:Lucee    文件:HTTPEngine4Impl.java   
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username,String password, boolean preAuth) {
       // set Username and Password
       if(!StringUtil.isEmpty(username,true)) {
           if(password==null)password="";
           CredentialsProvider cp = new BasicCredentialsProvider();
           builder.setDefaultCredentialsProvider(cp);

           cp.setCredentials(
               new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
               new UsernamePasswordCredentials(username,password));



           BasicHttpContext httpContext = new BasicHttpContext();
           if(preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
           }
           return httpContext;
       }
       return null;
}
项目:atlassian    文件:CrowdSvcImpl.java   
protected HttpClientContext buildLocalContext(boolean forceFresh) throws Exception {
    log.trace("buildLocalContext");

    if (this.localContext == null || forceFresh) {

        // 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
        localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);
        return localContext;
    } else {
        return this.localContext;
    }

}
项目:fcrepo4-client    文件:HttpHelper.java   
/**
 * Create an HTTP helper with a pre-configured HttpClient instance.
 * @param repositoryURL Fedora base URL.
 * @param httpClient Pre-configured HttpClient instance.
 * @param readOnly If true, throw an exception when an update is attempted.
**/
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
    this.repositoryURL = repositoryURL;
    this.httpClient = httpClient;
    this.readOnly = readOnly;

    // Use pre-emptive Auth whether the repository is actually protected or not.
    final URI uri = URI.create(repositoryURL);
    final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    this.httpContext = localContext;
}