Java 类org.apache.http.client.CredentialsProvider 实例源码

项目:ticketing-service-paqx-parent-sample    文件:TicketingIntegrationService.java   
private void delete(String url) throws IOException, HttpException {
    CredentialsProvider credentials = credentialsProvider();
    CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

    try {
        HttpDelete httpDelete = new HttpDelete(url);
        httpDelete.setHeader("Accept", "application/json");

        System.out.println("Executing request " + httpDelete.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpDelete);
        try {
            LOG.debug("----------------------------------------");
            LOG.debug((String)response.getStatusLine().getReasonPhrase());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
项目:Reer    文件:HttpClientConfigurer.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
项目:dhus-core    文件:ODataProductSynchronizer.java   
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
           new UsernamePasswordCredentials(serviceUser, servicePass));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
项目:Reer    文件:HttpClientConfigurer.java   
private void configureCredentials(HttpClientBuilder builder, CredentialsProvider credentialsProvider, Collection<Authentication> authentications) {
    if(authentications.size() > 0) {
        useCredentials(credentialsProvider, AuthScope.ANY_HOST, AuthScope.ANY_PORT, authentications);

        // Use preemptive authorisation if no other authorisation has been established
        builder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme(), isPreemptiveEnabled(authentications)));
    }
}
项目:Reer    文件:HttpClientConfigurer.java   
private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) {
    Credentials httpCredentials;

    for (Authentication authentication : authentications) {
        String scheme = getAuthScheme(authentication);
        PasswordCredentials credentials = getPasswordCredentials(authentication);

        if (authentication instanceof AllSchemesAuthentication) {
            NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
            httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
            credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials);

            LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM);
        }

        httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword());
        credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials);
        LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme);
    }
}
项目:jspider    文件:HttpClientExecutor.java   
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) {
    HttpContext httpContext = new HttpClientContext();

    if (cookieStore != null) {
        httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    }

    if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()),
                new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword()));
        httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);
    }

    return httpContext;
}
项目:SensorThingsProcessor    文件:AuthBasic.java   
@Override
public void setAuth(SensorThingsService service) {
    try {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(
                new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}
项目:PeSanKita-android    文件:LegacyMmsConnection.java   
protected CloseableHttpClient constructHttpClient() throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL                 mmsc          = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
项目: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;
}
项目:dhus-core    文件:ODataClient.java   
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
项目:ticketing-service-paqx-parent-sample    文件:TicketingIntegrationService.java   
private Map put(String url, String data) throws IOException, HttpException {
    Map<String,Object> map = null;
    CredentialsProvider credentials = credentialsProvider();
    CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

    try {
        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("Accept", "application/json");
        httpPut.setHeader("Content-Type", "application/json");
        HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
        httpPut.setEntity(entity);

        System.out.println("Executing request " + httpPut.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPut);
        try {
            LOG.debug("----------------------------------------");
            LOG.debug((String)response.getStatusLine().getReasonPhrase());
            String responseBody = EntityUtils.toString(response.getEntity());
            LOG.debug(responseBody);
            Gson gson = new Gson();
            map = new HashMap<String,Object>();
            map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
            LOG.debug(responseBody);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }

    return map;
}
项目:es-log4j2-appender    文件:ElasticBulkSender.java   
public ElasticBulkSender(String user, String password, HttpHost... hosts) {
    this.user = user;
    this.password = password;
    this.hosts = hosts;
    this.restClient = RestClient.builder(hosts)
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    if (!Strings.isBlank(user)) {
                        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    } else {
                        return httpClientBuilder;
                    }
                }
            })
            .build();
}
项目:SensorThingsManager    文件:AuthBasic.java   
@Override
public void setAuth(SensorThingsService service) {
    try {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(
                new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}
项目:lams    文件:RequestAuthCache.java   
private void doPreemptiveAuth(
        final HttpHost host,
        final AuthScheme authScheme,
        final AuthState authState,
        final CredentialsProvider credsProvider) {
    String schemeName = authScheme.getSchemeName();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
    }

    AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
    Credentials creds = credsProvider.getCredentials(authScope);

    if (creds != null) {
        authState.setState(AuthProtocolState.SUCCESS);
        authState.update(authScheme, creds);
    } else {
        this.log.debug("No credentials for preemptive authentication");
    }
}
项目:teamcity-msteams-notifier    文件:MsTeamsNotificationImpl.java   
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;

if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));

          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }

          this.client = clientBuilder.build();
}
  }
项目:boohee_v5.6    文件:AsyncHttpClient$3.java   
public void process(HttpRequest request, HttpContext context) throws HttpException,
        IOException {
    AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope");
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" +
            ".credentials-provider");
    HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host");
    if (authState.getAuthScheme() == null) {
        Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName
                (), targetHost.getPort()));
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:Cognizant-Intelligent-Test-Scripter    文件:RemoteProxy.java   
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {

        prop = decrypt(prop);

        String proxyHost = prop.getProperty("proxyHost");
        int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
        String proxyUserDomain = prop.getProperty("proxyUserDomain");
        String proxyUser = prop.getProperty("proxyUser");
        String proxyPassword = prop.getProperty("proxyPassword");

        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
        if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
            credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        builder.setProxy(proxy);
        builder.setDefaultCredentialsProvider(credsProvider);
        HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
        return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);

    }
项目: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);
    }
}
项目:Cable-Android    文件:LegacyMmsConnection.java   
protected CloseableHttpClient constructHttpClient() throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL                 mmsc          = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
项目: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);
    }
}
项目:elasticsearch-full    文件:XPackBaseDemo.java   
@Before
public void setUp() throws Exception {
    /**
     * 如果es集群安装了x-pack插件则以此种方式连接集群
     * 1. java客户端的方式是以tcp协议在9300端口上进行通信
     * 2. http客户端的方式是以http协议在9200端口上进行通信
     */
    Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build();
    client = new PreBuiltXPackTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    elasticsearchTemplate = new ElasticsearchTemplate(client);
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("elastic", "changeme"));
    restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            }).build();
}
项目: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;
}
项目:yunpian-java-sdk    文件:AsyncClientAuthentication.java   
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
项目:Brutusin-RPC    文件:HttpEndpoint.java   
public static void main(String[] args) throws Exception {

        HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
            public HttpClientContext create() {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
                        new UsernamePasswordCredentials("user", "password"));
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                return context;
            }
        };

        HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);

        HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
        if (resp.isIsBinary()) {
            System.out.println("binary");
            System.out.println(resp.getInputStream().getName());
        } else {
            System.out.println(resp.getRpcResponse().getResult());
        }
    }
项目:Peking-University-Open-Research-Data-Platform    文件:DataCiteRESTfullClient.java   
public DataCiteRESTfullClient(String url, String username, String password) {
    this.url = url;
    try {
        context = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);

        httpClient = HttpClients.createDefault();
    } catch (Exception ioe) {
        close();
        logger.log(Level.SEVERE,"Fail to init Client",ioe);
        throw new RuntimeException("Fail to init Client", ioe);
    }
}
项目:axon-eventstore    文件:ESHttpEventStore.java   
public ESHttpEventStore(final String identifier, final ThreadFactory threadFactory, final URL url, final CredentialsProvider credentialsProvider, final int longPollSec, final int connectTimeout,
      final int connectionRequestTimeout, final int socketTimeout) {
   super();
   this.identifier = identifier;
   this.threadFactory = threadFactory;
   this.url = url;
   this.credentialsProvider = credentialsProvider;
   this.longPollSec = longPollSec;
   this.connectTimeout = connectTimeout;
   this.connectionRequestTimeout = connectionRequestTimeout;
   this.socketTimeout = socketTimeout;
   this.open = false;
   this.hostAndPort = url.getHost() + ":" + url.getPort();
   this.host = url.getHost();
   atomFeedReader = new AtomFeedJsonReader();
}
项目: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);
}
项目:beyondj    文件:HttpSender.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }
            authState.setAuthScheme(authScheme);
            authState.setCredentials(creds);
        }
    }

}
项目: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;
}
项目:alexa-meets-polly    文件:Mp3Converter.java   
public static String convertMp3(final String mp3Path) throws URISyntaxException, IOException {
    // get credentials for webservice from application config
    final String apiKey = SkillConfig.getTranslatorConvertServiceUser();
    final String apiPass = SkillConfig.getTranslatorConvertServicePass();
    // build uri
    final String bucketName = SkillConfig.getS3BucketName();
    final URIBuilder uri = new URIBuilder(SkillConfig.getTranslatorConvertServiceUrl()).addParameter("bucket", bucketName).addParameter("path", mp3Path);
    // set up web request
    final HttpGet httpGet = new HttpGet(uri.build());
    httpGet.setHeader("Content-Type", "text/plain");
    // set up credentials
    final CredentialsProvider provider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiKey, apiPass);
    provider.setCredentials(AuthScope.ANY, credentials);
    // send request to convert webservice
    final HttpResponse response =
            HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build().execute(httpGet);

    //Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
    // work on response
    final HttpEntity entity = response.getEntity();
    return IOUtils.toString(entity.getContent(), "UTF-8");
}
项目:OHMS    文件:HttpUtil.java   
/**
 * Returns HttpClient with basic auth.
 *
 * @param userName the user name
 * @param password the password
 * @return the http client with basic auth
 */
private static HttpClient getHttpClientWithBasicAuth( final String userName, final String password )
{
    // check that userName is not null
    if ( StringUtils.isBlank( userName ) )
    {
        logger.warn( "In getHttpClientWithBasicAuth, userName is either null or blank." );
        return null;
    }
    // check that password is not null
    if ( StringUtils.isBlank( password ) )
    {
        logger.warn( "In getHttpClientWithBasicAuth, password is either null or blank." );
        return null;
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( userName, password );
    credentialsProvider.setCredentials( AuthScope.ANY, usernamePasswordCredentials );
    return HttpClientBuilder.create().setDefaultCredentialsProvider( credentialsProvider ).build();
}
项目:diadocsdk-java    文件:DiadocPreemptiveAuthRequestInterceptor.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    // If no auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials credentials = credentialsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (credentials != null) {
            authState.setAuthScheme(new DiadocAuthScheme());
            authState.setCredentials(credentials);
        }
    }
}
项目:meituanwaimai-sdk    文件:MtWmClientImpl.java   
public void setConfigStorage(MtWmConfigStorage configStorage) {

        this.configStorage = configStorage;

        String http_proxy_host = configStorage.getHttp_proxy_host();
        int http_proxy_port = configStorage.getHttp_proxy_port();
        String http_proxy_username = configStorage.getHttp_proxy_username();
        String http_proxy_password = configStorage.getHttp_proxy_password();

        final HttpClientBuilder builder = HttpClients.custom();
        if (StringUtils.isNotBlank(http_proxy_host)) {
            // 使用代理服务器
            if (StringUtils.isNotBlank(http_proxy_username)) {
                // 需要用户认证的代理服务器
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope(http_proxy_host, http_proxy_port),
                        new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
                builder
                        .setDefaultCredentialsProvider(credsProvider);
            }
            httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
        }
        httpClient = builder.build();
    }
项目:remote-files-sync    文件:RequestAuthCache.java   
private void doPreemptiveAuth(
        final HttpHost host,
        final AuthScheme authScheme,
        final AuthStateHC4 authState,
        final CredentialsProvider credsProvider) {
    final String schemeName = authScheme.getSchemeName();
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host);
    }

    final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName);
    final Credentials creds = credsProvider.getCredentials(authScope);

    if (creds != null) {
        if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
            authState.setState(AuthProtocolState.CHALLENGED);
        } else {
            authState.setState(AuthProtocolState.SUCCESS);
        }
        authState.update(authScheme, creds);
    } else {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "No credentials for preemptive authentication");
        }
    }
}
项目:TextSecure    文件:MmsConnection.java   
protected CloseableHttpClient constructHttpClient()
    throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL mmsc = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent("Android-Mms/2.0")
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
项目:purecloud-iot    文件:WinHttpClients.java   
private static HttpClientBuilder createBuilder() {
    if (isWinAuthAvailable()) {
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null))
                .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null))
                .build();
        final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider());
        return HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credsProvider)
                .setDefaultAuthSchemeRegistry(authSchemeRegistry);
    } else {
        return HttpClientBuilder.create();
    }
}
项目:binjr    文件:HttpClientKerberosDoAS.java   
private HttpClient getHttpClient() {

        Credentials use_jaas_creds = new Credentials() {
            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }
        };

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
        Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build();

        return httpclient;
    }
项目:api-snippets    文件:lookup-get-addon-payfone-1.6.x.java   
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope("lookups.twilio.com", 80),
            new UsernamePasswordCredentials("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "your_auth_token"));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("https://lookups.twilio.com/v1/PhoneNumbers/+16502530000/?AddOns=payfone_tcpa_compliance&AddOns.payfone_tcpa_compliance.RightPartyContactedDate=20160101");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
项目:rundeck-device42-nodes-plugin    文件:AbstractAsynchronousRestClient.java   
/**
 * Create the HTTP clean with basic authentication mechanism using specified
 * credentials
 * 
 * @param username
 *            Authentication username
 * @param password
 *            Authentication password
 * @return
 */
protected static CloseableHttpClient createHttpClient(String username, String password) {
    SSLContext sslContext = createSslContext();
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    List<Header> headers = Arrays.asList(header);

    return HttpClients.custom()
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .setSSLSocketFactory(sslSocketFactory)
            .setDefaultCredentialsProvider(credentialsProvider)
            .setDefaultHeaders(headers)
            .build();
}
项目:crauler_ISI    文件:GenericRestClientAuth.java   
public static void getConnection(String username, String password, String API, int port, String method, String CollObject) throws ClientProtocolException, IOException {
    HttpHost targetHost = new HttpHost(API, port, "https");
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

    CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

    // create a GET method that queries some API operation
    HttpGet request = new HttpGet(method);

    try {
        // execute the operation
        HttpResponse response = client.execute(targetHost, request);

        // print the status and the contents of the response
        System.out.println(response.getStatusLine());

        JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
        JSONArray array = jsonObj.getJSONArray(CollObject);

    } finally {
        // release any connection resources used by the method
        client.close();
    }
}