List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:org.glassfish.jersey.apache.connector.AuthTest.java
@Test public void testPreemptiveAuthPost() { CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); ClientConfig cc = new ClientConfig(); cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider) .property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true); cc.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(cc); WebTarget r = client.target(getBaseUri()); assertEquals("POST", r.request().post(Entity.text("POST"), String.class)); }
From source file:org.alfresco.cacheserver.http.CacheHttpClient.java
private CloseableHttpClient getHttpClient(HttpHost target, HttpClientContext localContext, String username, String password) {/*from ww w .j a v a2 s . co m*/ ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { try { return Long.parseLong(value) * 1000; } catch (NumberFormatException ignore) { } } } HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST); if ("www.naughty-server.com".equalsIgnoreCase(target.getHostName())) { // Keep alive for 5 seconds only return 5 * 1000; } else { // otherwise keep alive for 30 seconds return 30 * 1000; } } }; HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .setExpectContinueEnabled(true) // .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig) .setDefaultCredentialsProvider(credsProvider).setKeepAliveStrategy(keepAliveStrategy) .setRetryHandler(retryHandler).build(); return httpclient; }
From source file:org.glassfish.jersey.apache.connector.AuthTest.java
@Test @Ignore("JERSEY-1750: Cannot retry request with a non-repeatable request entity. How to buffer the entity?" + " Allow repeatable write in jersey?") public void testAuthPost() { CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); ClientConfig cc = new ClientConfig(); cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider); cc.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(cc); WebTarget r = client.target(getBaseUri()).path("test"); assertEquals("POST", r.request().post(Entity.text("POST"), String.class)); }
From source file:org.glassfish.jersey.apache.connector.AuthTest.java
@Test @Ignore("JERSEY-1750: Cannot retry request with a non-repeatable request entity. How to buffer the entity?" + " Allow repeatable write in jersey?") public void testAuthInteractivePost() { CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); ClientConfig cc = new ClientConfig(); cc.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider); cc.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(cc); WebTarget r = client.target(getBaseUri()).path("test"); assertEquals("POST", r.request().post(Entity.text("POST"), String.class)); }
From source file:org.jboss.teiid.quickstart.PortfolioClient.java
public void resteasyHttpBackendClient() { System.out.println("\nResteasy Client API with HTTP client as engine"); HttpHost targetHost = new HttpHost("localhost", 8080, "http"); // 1. Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // 2. Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // 3. Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // 4. Create client executor and proxy HttpClientBuilder builder = HttpClientBuilder.create(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD); credsProvider.setCredentials(scope, credentials); builder.setDefaultCredentialsProvider(credsProvider); HttpClient httpClient = builder.build(); // 5. Create ResteasyClient with http client as engine ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, localContext); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); // 6. Execute Rest call via ResteasyClient String authString = getBasicAuthentication(); for (String api : apis) { ResteasyWebTarget target = client.target(api); Response response = target.request().header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, authString).get(); if (response.getStatus() == 200) { String value = response.readEntity(String.class); System.out.println(value); response.close();//from ww w . ja v a 2 s .c o m } else { handleError(response); } } }
From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java
private void setAuth(AuthConfiguration authConfiguration, HttpClientBuilder builder) throws InitializationException { if (!Strings.isNullOrEmpty(authConfiguration.getUsername())) { Credentials credentials = new UsernamePasswordCredentials(authConfiguration.getUsername(), authConfiguration.getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials); builder.addInterceptorFirst((HttpRequestInterceptor) (request, context) -> { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { //log.debug("SETTING CREDS"); //log.info("Preemptive AuthState: {}", authState); authState.update(new BasicScheme(), credentials); }//from w ww . j a v a2s . com }); } else { log.error("Username can't be blank for basic auth."); throw new InitializationException("Username blank for basic auth"); } }
From source file:org.alfresco.test.util.AlfrescoHttpClient.java
/** * Get basic http client with basic credential. * @param username String username // ww w . j a va 2 s.c om * @param password String password * @return {@link HttpClient} client */ public HttpClient getHttpClientWithBasicAuth(String username, String password) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); return client; }
From source file:io.kyligence.benchmark.loadtest.client.RestClient.java
private void init(String host, int port, String userName, String password) { this.host = host; this.port = port; this.userName = userName; this.password = password; this.baseUrl = "http://" + host + ":" + port + "/kylin/api"; client = new DefaultHttpClient(); if (userName != null && password != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password); provider.setCredentials(AuthScope.ANY, credentials); client.setCredentialsProvider(provider); }//from w w w . ja v a 2s .c o m client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, ONE_HOUR_IN_MS); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, ONE_HOUR_IN_MS); }
From source file:kuona.jenkins.analyser.JenkinsClient.java
/** * Create an authenticated Jenkins HTTP client * * @param uri Location of the jenkins server (ex. http://localhost:8080) * @param username Username to use when connecting * @param password Password or auth token to use when connecting */// www . j a v a 2s .c o m public JenkinsClient(Project project, URI uri, String username, String password) { this(project, uri); if (isNotBlank(username)) { CredentialsProvider provider = client.getCredentialsProvider(); AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(scope, credentials); localContext = new BasicHttpContext(); localContext.setAttribute("preemptive-auth", new BasicScheme()); client.addRequestInterceptor(new PreemptiveAuth(), 0); } }
From source file:kuona.client.JenkinsHttpClient.java
/** * Create an authenticated Jenkins HTTP client * * @param uri Location of the jenkins server (ex. http://localhost:8080) * @param username Username to use when connecting * @param password Password or auth token to use when connecting *///from ww w. java2s . c o m public JenkinsHttpClient(Project project, URI uri, String username, String password) { this(project, uri); if (isNotBlank(username)) { CredentialsProvider provider = client.getCredentialsProvider(); AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm"); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(scope, credentials); localContext = new BasicHttpContext(); localContext.setAttribute("preemptive-auth", new BasicScheme()); client.addRequestInterceptor(new PreemptiveAuth(), 0); } }