Example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider.

Prototype

public BasicCredentialsProvider() 

Source Link

Document

Default constructor.

Usage

From source file:io.pivotal.xd.chaoslemur.infrastructure.StandardDirectorUtils.java

private static RestTemplate createRestTemplate(String host, String username, String password,
        Set<ClientHttpRequestInterceptor> interceptors) throws GeneralSecurityException {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(host, 25555),
            new UsernamePasswordCredentials(username, password));

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();//from   www  . ja v  a2s  .c o  m

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(connectionFactory).build();

    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    restTemplate.getInterceptors().addAll(interceptors);

    return restTemplate;
}

From source file:com.restfiddle.handler.http.auth.BasicAuthHandler.java

/**
 * TODO : Not used anywhere right now.//from  ww w .  j  a va  2  s .c  om
 */
public CredentialsProvider prepareBasicAuth(String userName, String password) {
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, userName);
    provider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials);

    return provider;
}

From source file:net.networksaremadeofstring.rhybudd.ZenossAPICore.java

@Override
public boolean Login(ZenossCredentials credentials) throws Exception {
    if (credentials.URL.contains("https://")) {
        this.PrepareSSLHTTPClient();
    } else {/* ww w. j  av  a 2  s  .  c  o m*/
        this.PrepareHTTPClient();
        //httpclient = new DefaultHttpClient();
    }

    if (!credentials.BAUser.equals("") || !credentials.BAPassword.equals("")) {
        //Log.i("Auth","We have some auth credentials");
        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(credentials.BAUser, credentials.BAPassword));
        httpclient.setCredentialsProvider(credProvider);
    }

    HttpPost httpost = new HttpPost(credentials.URL + "/zport/acl_users/cookieAuthHelper/login");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("__ac_name", credentials.UserName));
    nvps.add(new BasicNameValuePair("__ac_password", credentials.Password));
    nvps.add(new BasicNameValuePair("submitted", "true"));
    nvps.add(new BasicNameValuePair("came_from", credentials.URL + "/zport/dmd"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // Response from POST not needed, just the cookie
    HttpResponse response = httpclient.execute(httpost);

    // Consume so we can reuse httpclient
    response.getEntity().consumeContent();

    //Set the variables for later
    this.ZENOSS_INSTANCE = credentials.URL;
    this.ZENOSS_USERNAME = credentials.UserName;
    this.ZENOSS_PASSWORD = credentials.Password;

    Log.e("CheckLoggedIn", Integer.toString(response.getStatusLine().getStatusCode()));

    reqCount++;
    return this.CheckLoggedIn();
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

private CloseableHttpClient createAuthenticatedClient() {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(config.getUser(), config.getApiKey()));

    return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent)
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCredentialsProvider(credentialsProvider)
            .build();// w  w w .j a v a 2s  . c om
}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);//from   w  w  w  . j a  v a2  s  .co m

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:$.HelloWorldWebScriptIT.java

@Test
    public void testWebScriptCall() throws Exception {
        String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
        String expectedResponse = "Message: 'Hello from JS!' 'HelloFromJava'";

        // Login credentials for Alfresco Repo
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "admin");
        provider.setCredentials(AuthScope.ANY, credentials);

        // Create HTTP Client with credentials
        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

        // Execute Web Script call
        try {/*from w  ww. j a v  a  2 s .  co  m*/
            HttpGet httpget = new HttpGet(webscriptURL);
            HttpResponse httpResponse = httpclient.execute(httpget);
            assertEquals("Incorrect HTTP Response Status", HttpStatus.SC_OK,
                    httpResponse.getStatusLine().getStatusCode());
            HttpEntity entity = httpResponse.getEntity();
            assertNotNull("Response from Web Script is null", entity);
            assertEquals("Incorrect Web Script Response", expectedResponse, EntityUtils.toString(entity));
        } finally {
            httpclient.close();
        }
    }

From source file:goofyhts.torrentkinesis.test.HttpTest.java

@Test
public void testGet() {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpClientContext context = new HttpClientContext();
        CredentialsProvider credProv = new BasicCredentialsProvider();
        credProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("root", "Whcinhry21#"));
        context.setCredentialsProvider(credProv);
        HttpGet httpGet = new HttpGet("http://localhost:8150/gui/token.html");

        CloseableHttpResponse response = client.execute(httpGet, context);
        String responseBody = IOUtils.toString(response.getEntity().getContent());
        System.out.println(responseBody);
        Document doc = Jsoup.parse(responseBody);
        System.out.println(doc.getElementById("token").text());
    } catch (ClientProtocolException e) {
        e.printStackTrace();//from w w w. j av a2  s  .c o m
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Assert.assertTrue(true);
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestTemplateProvider.java

public RestTemplate createTemplate(final String host, final Integer port, final String username,
        final String password) {
    Preconditions.checkArgument(StringUtils.isNotBlank(host));
    Preconditions.checkArgument(port != null);
    Preconditions.checkArgument(StringUtils.isNotBlank(username));
    Preconditions.checkArgument(StringUtils.isNotBlank(password));

    final AuthScope authscope = new AuthScope(host, port.intValue());
    final Credentials credentials = new UsernamePasswordCredentials(username, password);
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authscope, credentials);

    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    final CloseableHttpClient httpClient = clientBuilder.build();

    final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

From source file:org.mycontroller.standalone.restclient.RestFactory.java

public T createAPI(URI uri, String userName, String password) {
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(userName, 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(targetHost, basicAuth);
    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//from   www .java2 s. c o m
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context);

    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    client.register(JacksonJaxbJsonProvider.class);
    client.register(RequestLogger.class);
    client.register(ResponseLogger.class);
    ProxyBuilder<T> proxyBuilder = client.target(uri).proxyBuilder(proxyClazz);
    return proxyBuilder.build();
}