org.apache.http.client.protocol.HttpClientContext#setCredentialsProvider ( )源码实例Demo

下面列出了org.apache.http.client.protocol.HttpClientContext#setCredentialsProvider ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hop   文件: HopServer.java
private void addCredentials( HttpClientContext context ) {

    String host = environmentSubstitute( hostname );
    int port = Const.toInt( environmentSubstitute( this.port ), 80 );
    String userName = environmentSubstitute( username );
    String password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    String proxyHost = environmentSubstitute( proxyHostname );

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
    if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
      host = "127.0.0.1";
    }
    provider.setCredentials( new AuthScope( host, port ), credentials );
    context.setCredentialsProvider( provider );
    // Generate BASIC scheme object and add it to the local auth cache
    HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put( target, basicAuth );
    context.setAuthCache( authCache );
  }
 
private HttpClientContext setupContext() {
    final HttpClientContext context = HttpClientContext.create();
    if (baseUri.contains("@") || springCloudConfigClientConfig.usernameAndPasswordSet()) {
        final AuthCache authCache = InMemoryAuthCache.INSTANCE;
        authCache.put(HttpHost.create(baseUri), new BasicScheme());
        context.setAuthCache(authCache);
        if (springCloudConfigClientConfig.usernameAndPasswordSet()) {
            final CredentialsProvider provider = new BasicCredentialsProvider();
            final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                    springCloudConfigClientConfig.username.get(), springCloudConfigClientConfig.password.get());
            provider.setCredentials(AuthScope.ANY, credentials);
            context.setCredentialsProvider(provider);
        }
    }
    return context;
}
 
源代码3 项目: 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;
}
 
源代码4 项目: aws-sdk-java-v2   文件: ApacheUtils.java
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.host(), proxyConfiguration.port());
        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);
    }
}
 
源代码5 项目: 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());
        }
    }
 
源代码6 项目: nexus-public   文件: FormatClientSupport.java
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

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

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
源代码7 项目: nexus-public   文件: FormatClientSupport.java
protected CloseableHttpResponse execute(final HttpUriRequest request, String username, String password)
    throws IOException
{
  log.debug("Authorizing request for {} using credentials provided for username: {}",
      request.getURI(), username);
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

  HttpHost host = URIUtils.extractHost(request.getURI());

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

  HttpClientContext clientContext = new HttpClientContext(httpClientContext);
  clientContext.setAuthCache(authCache);
  clientContext.setCredentialsProvider(credsProvider);

  return execute(request, clientContext);
}
 
源代码8 项目: logsniffer   文件: HttpPublisher.java
/**
 * Init method for this publisher.
 * 
 * @param velocityRenderer
 *            the velocityRenderer to set
 * @param httpClient
 *            http client
 */
protected void init(final VelocityEventRenderer velocityRenderer,
		final HttpClient httpClient) {
	this.velocityRenderer = velocityRenderer;
	this.httpClient = httpClient;
	if (getHttpAuthentication() != null) {
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,
				AuthScope.ANY_PORT), new UsernamePasswordCredentials(
				getHttpAuthentication().getUsername(),
				getHttpAuthentication().getPassword()));
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
	}
}
 
源代码9 项目: 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;
}
 
/**
 * HttpClient does not support preemptive authentication out of the box, because if misused or used incorrectly the
 * preemptive authentication can lead to significant security issues, such as sending user credentials in clear text
 * to an unauthorized third party. Therefore, users are expected to evaluate potential benefits of preemptive
 * authentication versus security risks in the context of their specific application environment.
 *
 * Nonetheless one can configure HttpClient to authenticate preemptively by prepopulating the authentication data cache.
 *
 * @see https://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
 *
 * @param target target URI
 * @param auth login data
 * @return
 */
private HttpClientContext buildPreemptiveAuthRequestContext( final URI target, final AuthenticationData auth ) {

  if ( target == null || auth == null || StringUtils.isEmpty( auth.getUsername() ) ) {
    return null; // nothing to do here; if no credentials were passed, there's no need to create a preemptive auth Context
  }

  HttpHost targetHost = URIUtils.extractHost( target );

  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials( new AuthScope( targetHost.getHostName(), targetHost.getPort() ),
      new UsernamePasswordCredentials( auth.getUsername(), auth.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 );

  HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider( credsProvider );
  context.setAuthCache( authCache );

  return context;
}
 
源代码11 项目: pentaho-kettle   文件: SlaveServer.java
private void addCredentials( HttpClientContext context ) {
  String userName;
  String password;
  String host;
  int port;
  String proxyHost;
  lock.readLock().lock();
  try {
    host = environmentSubstitute( hostname );
    port = Const.toInt( environmentSubstitute( this.port ), 80 );
    userName = environmentSubstitute( username );
    password = Encr.decryptPasswordOptionallyEncrypted( environmentSubstitute( this.password ) );
    proxyHost = environmentSubstitute( proxyHostname );
  } finally {
    lock.readLock().unlock();
  }
  CredentialsProvider provider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( userName, password );
  if ( !Utils.isEmpty( proxyHost ) && host.equals( "localhost" ) ) {
    host = "127.0.0.1";
  }
  provider.setCredentials( new AuthScope( host, port ), credentials );
  context.setCredentialsProvider( provider );
  // Generate BASIC scheme object and add it to the local auth cache
  HttpHost target = new HttpHost( host, port, isSslMode() ? HTTPS : HTTP );
  AuthCache authCache = new BasicAuthCache();
  BasicScheme basicAuth = new BasicScheme();
  authCache.put( target, basicAuth );
  context.setAuthCache( authCache );
}
 
源代码12 项目: knox   文件: GatewayBasicFuncTest.java
private String oozieQueryJobStatus( String user, String password, String id, int status ) throws Exception {
  driver.getMock( "OOZIE" )
      .expect()
      .method( "GET" )
      .pathInfo( "/v1/job/" + id )
      .respond()
      .status( HttpStatus.SC_OK )
      .content( driver.getResourceBytes( "oozie-job-show-info.json" ) )
      .contentType( "application/json" );

  //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
  URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/job/" + id + ( driver.isUseGateway() ? "" : "?user.name=" + user ) );
  HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
  HttpClientBuilder builder = HttpClientBuilder.create();
  CloseableHttpClient client = builder.build();

  HttpClientContext context = HttpClientContext.create();
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(
      new AuthScope( targetHost ),
      new UsernamePasswordCredentials( user, password ) );
  context.setCredentialsProvider( credsProvider );

  // 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
  context.setAuthCache( authCache );

  HttpGet request = new HttpGet( url.toURI() );
  request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
  HttpResponse response = client.execute( targetHost, request, context );
  assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
  String json = EntityUtils.toString( response.getEntity() );
  return JsonPath.from(json).getString( "status" );
}
 
源代码13 项目: vscrawler   文件: VSCrawlerRoutePlanner.java
@Override
protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
    HttpClientContext httpClientContext = HttpClientContext.adapt(context);
    Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession);

    if (proxy == null) {
        return null;
    }
    if (log.isDebugEnabled()) {
        log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort());
    }
    context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy);
    crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy);

    if (proxy.getAuthenticationHeaders() != null) {
        for (Header header : proxy.getAuthenticationHeaders()) {
            request.addHeader(header);
        }
    }

    if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) {
        BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider();
        httpClientContext.setCredentialsProvider(credsProvider1);
        credsProvider1.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
    }
    return new HttpHost(proxy.getIp(), proxy.getPort());
}
 
源代码14 项目: cs-actions   文件: ContextBuilder.java
public HttpClientContext build() {
    if (StringUtils.isEmpty(preemptiveAuth)) {
        preemptiveAuth = "true";
    }
    HttpClientContext context = HttpClientContext.create();
    if (authTypes.size() == 1 && Boolean.parseBoolean(preemptiveAuth) && !authTypes.contains(AuthTypes.ANONYMOUS)) {
        AuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()),
                authSchemeLookup.lookup(authTypes.iterator().next()).create(context));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    }
    return context;
}
 
源代码15 项目: document-management-software   文件: HttpRestWb.java
private static void uploadDocument(CloseableHttpClient httpclient) throws IOException {

		System.out.println("uploadDocument(CloseableHttpClient)");
		
		URL url = new URL(BASE_PATH);
		
		HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
        
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());
        
		// Add AuthCache to the execution context
		HttpClientContext context = HttpClientContext.create();
		context.setCredentialsProvider(credsProvider);
		context.setAuthCache(authCache);
		
        HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/document/upload");
       
        File file = new File("c:/users/shatz/Downloads/logicaldocsecurity-171122130133.pdf");
        //File file = new File("C:/tmp/InvoiceProcessing01-workflow.png");  
                
		System.out.println(file.getName());	
		System.out.println(file.getAbsolutePath());	
		
		long folderID = 124358812L;
		
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();         
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		builder.addTextBody("filename", file.getName(), ContentType.TEXT_PLAIN);
		builder.addBinaryBody("filedata", file, ContentType.DEFAULT_BINARY, file.getName());
		builder.addTextBody("folderId", Long.toString(folderID), ContentType.TEXT_PLAIN);		
		
		// 
		HttpEntity entity = builder.build();
		httppost.setEntity(entity);
		
		CloseableHttpResponse response = httpclient.execute(httppost, context);
		
		int code = response.getStatusLine().getStatusCode();
		System.out.println("HTTPstatus code: "+ code);
		
		try {
			HttpEntity rent = response.getEntity();
			if (rent != null) {
				String respoBody = EntityUtils.toString(rent, "UTF-8");
				System.out.println(respoBody);
			}
		} finally {
			response.close();
		}
	}
 
源代码16 项目: ehousechina   文件: JenKinsBuildService.java
private HttpClientContext getHttpClientContext(){
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCredentialsProvider(this.getCredentialsProvider());
	httpClientContext.setAuthCache(this.getAuthCache());
	return httpClientContext;
}
 
@Test
public void givenServerThatIsBehindAuthorizationProxy_whenClientSendRequest_shouldAuthorizeProperly() throws IOException {
    //given
    proxyMock.stubFor(get(urlMatching("/private"))
      .willReturn(aResponse().proxiedFrom("http://localhost:8089/")));
    serviceMock.stubFor(get(urlEqualTo("/private"))
      .willReturn(aResponse().withStatus(200)));


    HttpHost proxy = new HttpHost("localhost", 8090);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

    // Client credentials
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxy),
      new UsernamePasswordCredentials("username_admin", "secret_password"));


    // 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(proxy, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);


    HttpClient httpclient = HttpClients.custom()
      .setRoutePlanner(routePlanner)
      .setDefaultCredentialsProvider(credentialsProvider)
      .build();


    //when
    final HttpGet httpGet = new HttpGet("http://localhost:8089/private");
    HttpResponse response = httpclient.execute(httpGet, context);

    //then
    assertEquals(response.getStatusLine().getStatusCode(), 200);
    proxyMock.verify(getRequestedFor(urlEqualTo("/private")).withHeader("Authorization", containing("Basic")));
    serviceMock.verify(getRequestedFor(urlEqualTo("/private")));
}
 
/**
 * Perform the request with the given URL and JSON data.
 *
 * @param requestString Server request relative URL
 * @param data          JSON data for the request
 * @return JSON results of the request
 * @throws IOException On query problems
 */
public String performPostRequest(String requestString, String data) throws IOException {
  HttpPost request = new HttpPost(getBaseUrl() + requestString);
  String json = null;

  request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE));
  request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, CONTENT_TYPE));
  request.setHeader(new BasicHeader(HttpHeaders.CONTENT_ENCODING, CONTENT_TYPE));

  HttpClientBuilder httpClientBuilder = HttpClients.custom()
      .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  final HttpClientContext context = HttpClientContext.create();
  if (credentials != null) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, credentials);

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

    // Add AuthCache to the execution context
    context.setCredentialsProvider(provider);
    context.setAuthCache(authCache);
  }

  CloseableHttpClient httpClient = httpClientBuilder.build();
  if (proxies.size() > 0) {
    // We only check the first proxy for now
    Proxy myProxy = proxies.get(0);
    HttpHost proxy = myProxy.getHttpHost();
    RequestConfig config = RequestConfig.custom()
        .setProxy(proxy)
        .setSocketTimeout(myProxy.getProxySocketTimeout())
        .setConnectTimeout(myProxy.getProxyConnectTimeout())
        .setConnectionRequestTimeout(myProxy.getProxyConnectionRequestTimeout())
        .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
        .build();
    request.setConfig(config);
  }
  try {
    logger.debug("------------------------------------------------");
    logger.debug("OSS Index POST: " + getBaseUrl() + requestString);
    logger.debug(data);
    logger.debug("------------------------------------------------");

    request.setEntity(new StringEntity(data));
    CloseableHttpResponse response = httpClient.execute(request, context);
    int code = response.getStatusLine().getStatusCode();
    if (code < 200 || code > 299) {
      throw new ConnectException(response.getStatusLine().getReasonPhrase() + " (" + code + ")");
    }
    json = EntityUtils.toString(response.getEntity(), "UTF-8");
  }
  catch (ParseException e) {
    throw new IOException(e);
  }
  finally {
    httpClient.close();
  }
  return json;
}
 
源代码19 项目: commons-vfs   文件: Http4FileProvider.java
/**
 * Create an {@link HttpClientContext} object for an http4 file system.
 *
 * @param builder Configuration options builder for http4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @param authData The {@code UserAuthentiationData} object
 * @return an {@link HttpClientContext} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientContext createHttpClientContext(final Http4FileSystemConfigBuilder builder,
        final GenericFileName rootName, final FileSystemOptions fileSystemOptions,
        final UserAuthenticationData authData) throws FileSystemException {

    final HttpClientContext clientContext = HttpClientContext.create();
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    clientContext.setCredentialsProvider(credsProvider);

    final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
            UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
    final String password = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
            UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())));

    if (username != null && !username.isEmpty()) {
        credsProvider.setCredentials(new AuthScope(rootName.getHostName(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
    }

    final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);

    if (proxyHost != null) {
        final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);

        if (proxyAuth != null) {
            final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth,
                    new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                            UserAuthenticationData.PASSWORD });

            if (proxyAuthData != null) {
                final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                        UserAuthenticatorUtils.toString(
                                UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)),
                        UserAuthenticatorUtils.toString(
                                UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null)));

                credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), AuthScope.ANY_PORT),
                        proxyCreds);
            }

            if (builder.isPreemptiveAuth(fileSystemOptions)) {
                final AuthCache authCache = new BasicAuthCache();
                final BasicScheme basicAuth = new BasicScheme();
                authCache.put(proxyHost, basicAuth);
                clientContext.setAuthCache(authCache);
            }
        }
    }

    return clientContext;
}
 
源代码20 项目: knox   文件: GatewayBasicFuncTest.java
private String oozieSubmitJob( String user, String password, String request, int status ) throws IOException, URISyntaxException {
    driver.getMock( "OOZIE" )
        .expect()
        .method( "POST" )
        .pathInfo( "/v1/jobs" )
        .respond()
        .status( HttpStatus.SC_CREATED )
        .content( driver.getResourceBytes( "oozie-jobs-submit-response.json" ) )
        .contentType( "application/json" );
    URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/jobs?action=start" + ( driver.isUseGateway() ? "" : "&user.name=" + user ) );
    HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.build();

    HttpClientContext context = HttpClientContext.create();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope( targetHost ),
        new UsernamePasswordCredentials( user, password ) );
    context.setCredentialsProvider( credsProvider );

    // 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
    context.setAuthCache( authCache );

    HttpPost post = new HttpPost( url.toURI() );
//      post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity( request, org.apache.http.entity.ContentType.create( "application/xml", StandardCharsets.UTF_8.name() ) );
    post.setEntity( entity );
    post.setHeader( "X-XSRF-Header", "ksdjfhdsjkfhds" );
    HttpResponse response = client.execute( targetHost, post, context );
    assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
    String json = EntityUtils.toString( response.getEntity() );

//      String json = given()
//          .log().all()
//          .auth().preemptive().basic( user, password )
//          .queryParam( "action", "start" )
//          .contentType( "application/xml;charset=UTF-8" )
//          .content( request )
//          .then()
//          .log().all()
//          .statusCode( status )
//          .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    return JsonPath.from(json).getString( "id" );
  }