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.temenos.useragent.generic.http.DefaultHttpClientHelper.java

/**
 * Builds and returns the basic authentication provider.
 * /*from  ww w .ja  v a2 s. c  om*/
 * @return
 */
public static CredentialsProvider getBasicCredentialProvider() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    ConnectionConfig config = ContextFactory.get().getContext().connectionCongfig();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            config.getValue(ConnectionConfig.USER_NAME), config.getValue(ConnectionConfig.PASS_WORD)));
    return credentialsProvider;
}

From source file:com.globo.aclapi.client.ClientAclAPI.java

private static HttpClient newDefaultHttpClient(SSLSocketFactory socketFactory, HttpParams params,
        ProxySelector proxySelector) {
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));

    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);

    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params) {
        @Override/*w ww .j  a v a2s.  com*/
        protected HttpContext createHttpContext() {
            HttpContext httpContext = super.createHttpContext();
            AuthSchemeRegistry authSchemeRegistry = new AuthSchemeRegistry();
            authSchemeRegistry.register("Bearer", new BearerAuthSchemeFactory());
            httpContext.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, authSchemeRegistry);
            AuthScope sessionScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM,
                    "Bearer");

            Credentials credentials = new TokenCredentials("");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(sessionScope, credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            return httpContext;
        }
    };
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));

    return httpClient;
}

From source file:sk.datalan.solr.impl.HttpClientUtil.java

public static HttpClientBuilder configureClient(final HttpClientConfiguration config) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // max total connections
    if (config.isSetMaxConnections()) {
        clientBuilder.setMaxConnTotal(config.getMaxConnections());
    }/* w w w  . j a  va  2 s .  c o  m*/

    // max connections per route
    if (config.isSetMaxConnectionsPerRoute()) {
        clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true);

    // connection timeout
    if (config.isSetConnectionTimeout()) {
        requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout());
    }

    // soucket timeout
    if (config.isSetSocketTimeout()) {
        requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    }

    // soucket timeout
    if (config.isSetFollowRedirects()) {
        requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects());
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    if (config.isSetUseRetry()) {
        if (config.getUseRetry()) {
            clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());
        } else {
            clientBuilder.setRetryHandler(NO_RETRY);
        }
    }

    // basic authentication
    if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword()));
    }

    if (config.isSetAllowCompression()) {
        clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    }

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return clientBuilder;
}

From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java

private static HttpClient httpClientWithPreemptiveAuth(HttpHost target, String username, String password) {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials(username, password));

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

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

private static CredentialsProvider getCredentialsProvider(String url, String user, String pwd)
        throws URISyntaxException, MalformedURLException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    URL uri = new URL(url);
    String domain = uri.getHost();
    domain = domain.startsWith("www.") ? domain.substring(4) : domain;
    credsProvider.setCredentials(new AuthScope(domain, uri.getPort()),
            (Credentials) new UsernamePasswordCredentials(user, pwd));
    return credsProvider;
}

From source file:aajavafx.LoginController.java

public static String getPassword(String userName) throws MalformedURLException, JSONException, IOException {
    String password = "";

    Managers manager = new Managers();
    Managers myManager = new Managers();
    Gson gson = new Gson();

    JSONObject jo = new JSONObject();
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("ADMIN", "password");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/managers/username/" + userName);

    HttpResponse response = client.execute(get);
    System.out.println("RESPONSE IS: " + response);
    JSONArray jsonArray = new JSONArray(
            IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8")));
    System.out.println(jsonArray);
    for (int i = 0; i < jsonArray.length(); i++) {
        jo = (JSONObject) jsonArray.getJSONObject(i);
        manager = gson.fromJson(jo.toString(), Managers.class);
        if (manager.getManUsername().equals(userName)) {
            password = manager.getManPassword();
        }/*from   w w w  .  j  a v  a  2s.  c o m*/

        System.out.println(password);

    }
    return password;
}

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

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * /*from w  ww  .  j  av  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.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    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) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:com.streamreduce.util.HTTPUtils.java

/**
 * Opens a connection to the specified URL with the supplied username and password,
 * if supplied, and then reads the contents of the URL.
 *
 * @param url             the url to open and read from
 * @param method          the method to use for the request
 * @param data            the request body as string
 * @param mediaType       the media type of the request
 * @param username        the username, if any
 * @param password        the password, if any
 * @param requestHeaders  the special request headers to send
 * @param responseHeaders save response headers
 * @return the read string from the//from w w w.j a v  a2 s  .c om
 * @throws InvalidCredentialsException if the connection credentials are invalid
 * @throws IOException                 if there is a problem with the request
 */
public static String openUrl(String url, String method, String data, String mediaType,
        @Nullable String username, @Nullable String password, @Nullable List<Header> requestHeaders,
        @Nullable List<Header> responseHeaders) throws InvalidCredentialsException, IOException {

    String response = null;

    /* Set the cookie policy */
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    /* Set the user agent */
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT);

    HttpContext context = new BasicHttpContext();
    HttpRequestBase httpMethod;

    if (method.equals("DELETE")) {
        httpMethod = new HttpDelete(url);
    } else if (method.equals("GET")) {
        httpMethod = new HttpGet(url);
    } else if (method.equals("POST")) {
        httpMethod = new HttpPost(url);
    } else if (method.equals("PUT")) {
        httpMethod = new HttpPut(url);
    } else {
        throw new IllegalArgumentException("The method you specified is not supported.");
    }

    // Put data into the request for POST and PUT requests
    if (method.equals("POST") || method.equals("PUT") && data != null) {
        HttpEntityEnclosingRequestBase eeMethod = (HttpEntityEnclosingRequestBase) httpMethod;

        eeMethod.setEntity(new StringEntity(data, ContentType.create(mediaType, "UTF-8")));
    }

    /* Set the username/password if any */
    if (username != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
    }

    /* Add request headers if need be */
    if (requestHeaders != null) {
        for (Header header : requestHeaders) {
            httpMethod.addHeader(header);
        }
    }

    LOGGER.debug("Making HTTP request as " + (username != null ? username : "anonymous") + ": " + method + " - "
            + url);

    /* Make the request and read the response */
    try {
        HttpResponse httpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            response = EntityUtils.toString(entity);
        }
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        if (responseCode == 401 || responseCode == 403) {
            throw new InvalidCredentialsException("The connection credentials are invalid.");
        } else if (responseCode < 200 || responseCode > 299) {
            throw new IOException(
                    "Unexpected status code of " + responseCode + " for a " + method + " request to " + url);
        }

        if (responseHeaders != null) {
            responseHeaders.addAll(Arrays.asList(httpResponse.getAllHeaders()));
        }
    } catch (IOException e) {
        httpMethod.abort();
        throw e;
    }

    return response;
}

From source file:com.deliciousdroid.client.NetworkUtilities.java

/**
 * Attempts to authenticate to Pinboard using a legacy Pinboard account.
 * /*  w ww.  ja  v  a2 s  .co  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.
 */
public static boolean pinboardAuthenticate(String username, String password) {
    final HttpResponse resp;

    Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(DELICIOUS_AUTHORITY);
    builder.appendEncodedPath("v1/posts/update");
    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) {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Successful authentication");
            }
            return true;
        } else {
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Error authenticating" + resp.getStatusLine());
            }
            return false;
        }
    } catch (final IOException e) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "IOException when getting authtoken", e);
        }
        return false;
    } finally {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "getAuthtoken completing");
        }
    }
}

From source file:com.clonephpscrapper.utility.FetchPageWithProxy.java

public static String fetchPageSourcefromClientGoogleSecond(URI newurl) throws IOException {

    int portNo = generateRandomPort();
    CredentialsProvider credsprovider = new BasicCredentialsProvider();
    credsprovider.setCredentials(new AuthScope("195.154.161.103", portNo),
            new UsernamePasswordCredentials("mongoose", "Fjh30fi"));
    HttpHost proxy = new HttpHost("195.154.161.103", portNo);
    //-----------------------------------------------------------------------
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider)
            .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0")
            .setDefaultRequestConfig(requestConfig).setProxy(proxy).build();
    String responsebody = "";
    String responsestatus = null;
    try {/*from ww w.j ava  2s.c o  m*/
        HttpGet httpget = new HttpGet(newurl);
        httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpget.addHeader("Accept-Encoding", "gzip, deflate");
        httpget.addHeader("Accept-Language", "en-US,en;q=0.5");
        httpget.addHeader("Connection", "keep-alive");

        System.out.println("Response status" + httpget.getRequestLine());
        CloseableHttpResponse resp = httpclient.execute(httpget);
        responsestatus = resp.getStatusLine().toString();
        if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("400")
                || responsestatus.contains("401") || responsestatus.contains("402")
                || responsestatus.contains("403") || responsestatus.contains("407")
                || responsestatus.contains("404") || responsestatus.contains("405")
                || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999")
                || responsestatus.contains("ClientProtocolException")
                || responsestatus.contains("SocketTimeoutException") || responsestatus == null
                || "".equals(responsestatus)) {
            return null;
        } else {
            HttpEntity entity = resp.getEntity();
            System.out.println(resp.getStatusLine());
            if (entity != null) {
                //                    System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    responsebody = new StringBuilder().append(responsebody).append(inputLine).toString();
                }
                // writeResponseFile(responsebody, pagename);
            }
            EntityUtils.consume(entity);
        }
    } catch (IOException | IllegalStateException e) {
        return null;
    } finally {
        httpclient.close();
    }
    return responsebody;
}