Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

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

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:test.integ.be.fedict.hsm.rest.security.SecurityTest.java

@Test
public void testInvocation() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("username", "password"));
    HttpGet httpGet = new HttpGet(this.baseURL + "rest/security/test");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    String result = EntityUtils.toString(httpResponse.getEntity());
    LOG.debug("result: " + result);
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    assertEquals(200, statusCode);//from www  .jav a  2s. c  om
}

From source file:org.qi4j.library.shiro.UsernamePasswordHttpBasicTest.java

@Test
public void test() throws IOException {

    HttpGet get = new HttpGet(SECURED_SERVLET_PATH);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(UsernameFixtures.USERNAME, new String(UsernameFixtures.PASSWORD)));

    // First request with credentials
    String response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);

    // Cookies logging for the curious
    soutCookies(client.getCookieStore().getCookies());

    // Second request without credentials, should work thanks to sessions
    client.getCredentialsProvider().clear();
    response = client.execute(httpHost, get, responseHandler);
    assertEquals(ServletUsingSecuredService.OK, response);

}

From source file:org.jugvale.peoplemanagement.client.service.RESTPersonService.java

private void createClient() {
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    DefaultHttpClient httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            credentials);//from   www . j a  v  a 2  s . co m
    client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(httpClient)).build();
}

From source file:brooklyn.networking.cloudstack.HttpUtil.java

public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) {
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // TODO if supplier returns null, we may wish to defer initialization until url available?
    if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) {
        try {//from www  .j av a 2  s. co  m
            int port = (uri.getPort() >= 0) ? uri.getPort() : 443;
            SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustAllStrategy(),
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme sch = new Scheme("https", port, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
        } catch (Exception e) {
            LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri);
            throw Exceptions.propagate(e);
        }
    }

    // Set credentials
    if (uri != null && credentials.isPresent()) {
        String hostname = uri.getHost();
        int port = uri.getPort();
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get());
    }

    return httpClient;
}

From source file:org.jboss.as.test.integration.web.security.WebSecurityBASICTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from ww  w.  j a  v a2s . c om
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8080),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(URL);

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.jboss.as.test.integration.web.security.basic.WebSecurityBASICTestCase.java

@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/* w w w  .  j  av a 2  s .c  o m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.overlord.security.eval.webapp4.services.JaxrsService.java

/**
 * @return//from   ww  w .j av a 2 s. c om
 */
private ClientExecutor getSamlAssertionExecutor() {
    try {
        String username = "SAML-BEARER-TOKEN";
        String password = createSAMLAssertion();
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
        ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
        return clientExecutor;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sonar.plugins.buildstability.ci.teamcity.TeamCityServer.java

@Override
public void doLogin(DefaultHttpClient client) throws IOException {
    Credentials credentials = new UsernamePasswordCredentials(getUsername(), getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
}

From source file:com.networkmanagerapp.RestartWifi.java

/**
 * Requests the restart of WIFI in the background
 * @param arg0 the data to process in the background
 * @throws IOException caught locally. Catch throws NullPointerException, also caught internally.
 *//*from  w w  w.j a v  a 2 s. co  m*/
@Override
protected void onHandleIntent(Intent arg0) {
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    try {
        String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference",
                "");
        String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference",
                "192.168.1.1");
        String enc = URLEncoder.encode(ip, "utf-8");
        String scriptUrl = "http://" + enc + ":1080/cgi-bin/wifi.sh";
        HttpParams httpParams = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
        HttpHost targetHost = new HttpHost(enc, 1080, "http");
        DefaultHttpClient client = new DefaultHttpClient(httpParams);
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("root", password));
        HttpGet request = new HttpGet(scriptUrl);
        client.execute(targetHost, request);
    } catch (IOException ex) {
        try {
            Log.e("Network Manager reboot", ex.getLocalizedMessage());
        } catch (NullPointerException e) {
            Log.e("Network Manager reboot", "Rebooting, " + e.getLocalizedMessage());
        }

    } finally {
        mNM.cancel(R.string.wifi_service_restarted);
        stopSelf();
    }
}