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:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,
        String password, boolean preAuth) {
    // set Username and Password
    if (!StringUtil.isEmpty(username, true)) {
        if (password == null)
            password = "";
        CredentialsProvider cp = client.getCredentialsProvider();
        cp.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        BasicHttpContext httpContext = new BasicHttpContext();
        if (preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }/* w w w . ja  va 2s.c om*/
        return httpContext;
    }
    return null;
}

From source file:org.transdroid.daemon.util.HttpHelper.java

/**
 * Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods and basic
 * authentication//from  w  w  w  . j  a va 2  s . co m
 * @param sslTrustAll Whether to trust all SSL certificates
 * @param sslTrustkey A specific SSL key to accept exclusively
 * @param timeout The connection timeout for all requests
 * @param authAddress The authentication domain address
 * @param authPort The authentication domain port number
 * @return An HttpClient that should be stored locally and reused for every new request
 * @throws DaemonException Thrown when information (such as username/password) is missing
 */
public static DefaultHttpClient createStandardHttpClient(boolean userBasicAuth, String username,
        String password, boolean sslTrustAll, String sslTrustkey, int timeout, String authAddress, int authPort)
        throws DaemonException {

    // Register http and https sockets
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    SocketFactory https_socket = sslTrustAll ? new FakeSocketFactory()
            : sslTrustkey != null ? new FakeSocketFactory(sslTrustkey) : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("https", https_socket, 443));

    // Standard parameters
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, timeout);
    HttpConnectionParams.setSoTimeout(httpparams, timeout);
    if (userAgent != null) {
        HttpProtocolParams.setUserAgent(httpparams, userAgent);
    }

    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry),
            httpparams);

    // Authentication credentials
    if (userBasicAuth) {
        if (username == null || password == null) {
            throw new DaemonException(ExceptionType.AuthenticationFailure,
                    "No username or password was provided while we hadauthentication enabled");
        }
        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(authAddress, authPort, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }

    return httpclient;

}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

protected static DefaultHttpClient prepareHttpClient(URI uri, GHCredentials apiCredentials) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    httpClient.addRequestInterceptor(preemptiveAuth, 0);

    if (apiCredentials != null) {
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(apiCredentials.getUsername(), apiCredentials.getPassword()));
    }/*  w ww .  jav  a2  s.  c  o  m*/
    return httpClient;
}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse delete(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpDelete httpdel = new HttpDelete(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {

            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*from  ww  w.ja v a 2  s  .  c o m*/
            //this else part statements for other providers
            else {
                httpdel.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }

    TransportResponse transportResp = null;
    try {
        httpclient.execute(httpdel);
        //transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(), httpResp.getLocale());
    } finally {
        httpdel.releaseConnection();
    }
    return transportResp;

}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse get(TransportTools nuts)
        throws URISyntaxException, ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(nuts.urlString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {

            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*from  w  w w.ja  v a2s .c  om*/
            //this else part statements for other providers
            else {
                httpget.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }

    if (nuts.isQuery()) {
        URIBuilder uribuilder = new URIBuilder(nuts.urlString());
        uribuilder.setQuery(URLEncodedUtils.format(nuts.pairs(), nuts.encoding()));
        httpget.setURI(uribuilder.build());
    }

    TransportResponse transportResp = null;
    try {
        HttpResponse httpResp = httpclient.execute(httpget);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httpget.releaseConnection();
    }

    return transportResp;

}

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

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * //from   w  w  w  . j av  a 2 s. c  om
 * @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:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static void setProxy(DefaultHttpClient client, HttpUriRequest request, ProxyData proxy) {
    // set Proxy/*from w w  w . j  a v a 2s .  c o m*/
    if (ProxyDataImpl.isValid(proxy)) {
        HttpHost host = new HttpHost(proxy.getServer(), proxy.getPort() == -1 ? 80 : proxy.getPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
        if (!StringUtil.isEmpty(proxy.getUsername())) {

            client.getCredentialsProvider().setCredentials(new AuthScope(proxy.getServer(), proxy.getPort()),
                    new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
        }
    }
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

/**
 * This is here and needed because Alfresco CMIS and Chemistry don't play nice together for relationship deletes
 * as of Alfresco 3.4.2-5 & Chemistry 0.3.0. The problem is that for whatever reason Chemistry strips the "assoc:" prefix
 * off of the relationship ID that ends up on the end of the Delete URL, like this - /alfresco/service/cmis/rel/assoc:363.
 * Left to its own devices, Relationship.delete() will end up issuing a URL like /alfresco/service/cmis/rel/363, and Alfresco
 * will barf. This will hopefully be fixed in Alfesco 4.x.
 * @param proto/*w  w  w  . j  av a 2  s  .  c o m*/
 * @param host
 * @param port
 * @param user
 * @param pass
 * @param assocId
 * @return
 */
public static boolean deleteRelationship(String proto, String host, int port, String user, String pass,
        String assocId) {
    DefaultHttpClient client = new DefaultHttpClient();
    try {
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        HttpDelete delete = new HttpDelete(
                proto + "://" + host + ":" + port + "/alfresco/service/cmis/rel/" + assocId);
        log.info("Sending " + delete.toString());
        HttpResponse resp = client.execute(delete);
        if (resp.getStatusLine().getStatusCode() > 299) { // Alf returns "204 No Content" for success... :-(
            throw new RuntimeException("Get failed (" + resp.getStatusLine().getStatusCode() + ") because "
                    + resp.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return true;
}

From source file:com.amazonaws.util.HttpUtils.java

/**
 * Fetches a file from the URI given and returns an input stream to it.
 *
 * @param uri the uri of the file to fetch
 * @param config optional configuration overrides
 * @return an InputStream containing the retrieved data
 * @throws IOException on error/*from w  ww.  jav a2s . c o  m*/
 */
public static InputStream fetchFile(final URI uri, final ClientConfiguration config) throws IOException {

    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, getUserAgent(config));

    HttpConnectionParams.setConnectionTimeout(httpClientParams, getConnectionTimeout(config));
    HttpConnectionParams.setSoTimeout(httpClientParams, getSocketTimeout(config));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);

    if (config != null) {
        String proxyHost = config.getProxyHost();
        int proxyPort = config.getProxyPort();

        if (proxyHost != null && proxyPort > 0) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (config.getProxyUsername() != null && config.getProxyPassword() != null) {

                httpclient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(config.getProxyUsername(), config.getProxyPassword(),
                                config.getProxyWorkstation(), config.getProxyDomain()));
            }
        }
    }

    HttpResponse response = httpclient.execute(new HttpGet(uri));

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Error fetching file from " + uri + ": " + response);
    }

    return new HttpClientWrappingInputStream(httpclient, response.getEntity().getContent());
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

public static JsonNode getJsonNodeFromHttpGetResponse(String proto, String host, int port, String user,
        String pass, String path, HashMap params) throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {/* ww  w  . ja  v a2 s.  c  o  m*/
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        String paramStr = "";
        if (params != null && params.size() > 0) {
            Iterator<String> iter = params.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                //get.getParams().setParameter(key, params.get(key));
                if (!paramStr.equals("")) {
                    paramStr += "&";
                }
                paramStr += key + "=" + params.get(key);
            }
        }

        if (!paramStr.equals("")) {
            path += "?" + URLEncoder.encode(paramStr, "UTF-8").replace("+", "%20");
        }
        HttpGet get = new HttpGet(proto + host + ":" + port + path);
        log.info("Getting JsonNode for " + get.toString());
        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Get failed, can't build JsonNode because: " + resp.getStatusLine().getReasonPhrase());
        }
        org.apache.http.HttpEntity entity = resp.getEntity();
        return mapper.readValue(entity.getContent(), JsonNode.class);
    } finally {
        client.getConnectionManager().shutdown();
    }
}