Example usage for org.apache.http.client CredentialsProvider setCredentials

List of usage examples for org.apache.http.client CredentialsProvider setCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider setCredentials.

Prototype

void setCredentials(AuthScope authscope, Credentials credentials);

Source Link

Document

Sets the Credentials credentials for the given authentication scope.

Usage

From source file:com.pindroid.client.PinboardApi.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * //from  w ww .ja  v  a  2s . c o  m
 * @param username The user's username.
 * @param password The user's password.
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return The boolean result indicating whether the user was
 *         successfully authenticated.
 * @throws  
 */
public static String pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(AUTH_TOKEN_URI);
    Uri uri = builder.build();

    HttpGet request = new HttpGet(String.valueOf(uri));

    DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    CredentialsProvider provider = client.getCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    provider.setCredentials(SCOPE, credentials);

    try {
        resp = client.execute(request);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

            final HttpEntity entity = resp.getEntity();

            InputStream instream = entity.getContent();
            SaxTokenParser parser = new SaxTokenParser(instream);
            PinboardAuthToken token = parser.parse();
            instream.close();

            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
                Log.v(TAG, "AuthToken: " + token.getToken());
            }

            return token.getToken();
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return null;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return null;
    } catch (ParseException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "ParseException when getting authtoken", e);
        }
        return null;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean patch2DjangoJSONArray(Context context, JSONArray jsonArray, String uploadurl,
        String username, String password) {

    String response = "";

    try {//from  w w w . j  a v  a2s  . c  o m

        JSONObject obj = new JSONObject();
        obj.put("objects", jsonArray);
        JSONArray emptyarray = new JSONArray();
        obj.put("deleted_objects", emptyarray);

        CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        // Create a new HttpClient and Post Header
        HttpPatch httppatch = new HttpPatch(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppatch.setHeader("Content-type", "application/json");

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.setCredentialsProvider(credProvider);
        // ByteArrayEntity bae = new ByteArrayEntity(obj.toString()
        // .getBytes("UTF8"));

        StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        // bae.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
        // "application/json"));
        httppatch.setEntity(se);

        // Execute HTTP Post Request

        HttpResponse httpResponse = httpclient.execute(httppatch);

        response = httpResponse.getStatusLine().toString();

    } catch (ClientProtocolException e) {

    } catch (IOException e) {

    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (response.contains("ACCEPTED")) {
        return true;
    } else {
        return false;
    }

}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * For Basic auth, configure the context to do pre-emptive auth with the
 * credentials given./*from   w  ww  .j  ava  2  s  .com*/
 * @param httpContext The context in use for the requests.
 * @param serverURI The RTC server we will be authenticating against
 * @param userId The userId to login with
 * @param password The password for the User
 * @param listener A listen to log messages to, Not required
 * @throws IOException Thrown if anything goes wrong
 */
private static void handleBasicAuthChallenge(HttpClientContext httpContext, String serverURI, String userId,
        String password, TaskListener listener) throws IOException {

    URI uri;
    try {
        uri = new URI(serverURI);
    } catch (URISyntaxException e) {
        throw new IOException(Messages.HttpUtils_invalid_server(serverURI), e);
    }
    HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(userId, password));
    httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, 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(target, basicAuth);

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

From source file:org.elasticsearch.xpack.watcher.common.http.auth.basic.ApplicableBasicAuth.java

@Override
public void apply(CredentialsProvider credsProvider, AuthScope authScope) {
    credsProvider.setCredentials(authScope,
            new UsernamePasswordCredentials(auth.username, new String(auth.password.text(cryptoService))));
}

From source file:de.cuseb.bilderbuch.helpers.HttpClientProviderService.java

public HttpClient getHttpClientWithBasicAuth(String username, String password) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:de.simu.decomap.component.polling.impl.helper.RestClient.java

/**
 * //from  w  w w  . j  a  v  a 2s  .com
 * @param username
 *            The username for the authentification
 * @param password
 *            The password for the authentification
 */
public RestClient(String username, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username, password));
    //      HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    //setRequestFactory(new HttpComponentsClientHttpRequestFactory(httpClient));
}

From source file:com.nestorledon.employeedirectory.http.HttpComponentsClientHttpRequestFactoryBasicAuth.java

public HttpComponentsClientHttpRequestFactoryBasicAuth(String user, String password) {
    super();/*from  w  w w .j  ava  2  s.com*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(user, password));
    setHttpClient(HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build());
}

From source file:org.commonjava.indy.client.core.auth.BasicAuthenticator.java

@Override
public HttpClientContext decoratePrototypeContext(AuthScope scope, SiteConfig location, PasswordType type,
        HttpClientContext ctx) {//  ww w. j  a va 2 s.c  o m
    if (user != null) {
        final CredentialsProvider credProvider = new BasicCredentialsProvider();
        credProvider.setCredentials(scope, new UsernamePasswordCredentials(user, pass));
        ctx.setCredentialsProvider(credProvider);
    }
    return ctx;
}

From source file:com.msopentech.odatajclient.engine.client.http.AbstractNTLMAuthHttpClientFactory.java

@Override
public HttpClient createHttpClient(final HttpMethod method, final URI uri) {
    final DefaultHttpClient httpclient = (DefaultHttpClient) super.createHttpClient(method, uri);

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new NTCredentials(getUsername(), getPassword(), getWorkstation(), getDomain()));

    httpclient.setCredentialsProvider(credsProvider);

    return httpclient;
}

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  ww w .  j av a  2  s.  c o m*/
    } catch (IOException e) {
        e.printStackTrace();
    }
    //Assert.assertTrue(true);
}