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

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

Introduction

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

Prototype

public synchronized void setCredentialsProvider(final CredentialsProvider credsProvider) 

Source Link

Usage

From source file:org.lorislab.armonitor.client.MonitorClient.java

/**
 * Creates the monitor service./*  ww w.ja  v  a  2s. com*/
 *
 * @param url the URL.
 * @param username the user name.
 * @param password the password.
 * @return the monitor service.
 */
private static MonitorService createService(URL url, String username, String password, boolean auth) {
    ResteasyProviderFactory rpf = ResteasyProviderFactory.getInstance();
    RegisterBuiltin.register(rpf);

    String tmp = url.toString();
    if (!tmp.endsWith("/")) {
        tmp = tmp + "/";
    }
    tmp = tmp + APP_URL;

    if (auth) {
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient httpClient = new DefaultHttpClient();
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClient.setCredentialsProvider(provider);
        return ProxyFactory.create(MonitorService.class, tmp, new ApacheHttpClient4Executor(httpClient));
    }
    return ProxyFactory.create(MonitorService.class, tmp);
}

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Creates a {@link DefaultHttpClient} object.
 * //from www . jav  a  2s .  c o  m
 * @since 1.0
 * @param _credsProvider
 *            the object contains connect credential info like: User, Pwd, Host etc.
 * @param _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL
 *            true allow all hostname verifier for ssl.
 * @return the {@link DefaultHttpClient} object
 */
public static DefaultHttpClient createHttpClient(CredentialsProvider _credsProvider,
        boolean _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
    // -------------------------------------------------------------------
    // Example for _credsProvider
    //
    // String usr = getUser();
    // String pwd = getPassword();
    // DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    // CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(usr, pwd));
    // -------------------------------------------------------------------

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
    HttpConnectionParams.setSoTimeout(params, TIME_OUT);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    PlainSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory();
    SSLSocketFactory sslSocketFactory = null;

    if (_ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (Exception _e) {
            LL.e(_e.toString());
            sslSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        sslSocketFactory
                .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schReg.register(new Scheme("http", plainSocketFactory, 80));
    schReg.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    if (_credsProvider != null) {
        httpclient.setCredentialsProvider(_credsProvider);
    }
    return httpclient;
}

From source file:com.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./*from  w  w  w.ja v a  2 s  . co  m*/
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:org.lorislab.armonitor.util.RestClient.java

/**
 * Gets the rest-service client.//from ww  w.  j ava 2s . c  om
 *
 * @param <T> the rest-service client implementation.
 * @param clazz the rest-service class.
 * @param url the server URL.
 * @param username the username.
 * @param password the password.
 * @param auth the authentication flag.
 * @exception Exception if the method fails.
 *
 * @return the the rest-service client instance.
 */
public static <T> T getClient(final Class<T> clazz, String url, boolean auth, String username, char[] password)
        throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    if (url.startsWith(HTTPS)) {
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(),
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        httpClient.getConnectionManager().getSchemeRegistry()
                .register(new Scheme(HTTPS, 443, sslSocketFactory));
    }

    if (auth) {
        BasicCredentialsProvider provider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(username, new String(password));
        provider.setCredentials(AuthScope.ANY, credentials);
        httpClient.setCredentialsProvider(provider);
    }
    return ProxyFactory.create(clazz, url, new ApacheHttpClient4Executor(httpClient));
}

From source file:com.github.egonw.rrdf.RJenaHelper.java

public static StringMatrix sparqlRemoteNoJena(String endpoint, String queryString, String user, String password)
        throws Exception {
    StringMatrix table = null;/*from ww w.ja  va 2s . co m*/

    // use Apache for doing the SPARQL query
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Set credentials on the client
    if (user != null) {
        URL endpointURL = new URL(endpoint);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(endpointURL.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(user, password));
        httpclient.setCredentialsProvider(credsProvider);
    }

    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("query", queryString));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    HttpPost httppost = new HttpPost(endpoint);
    httppost.setEntity(entity);
    HttpResponse response = httpclient.execute(httppost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != 200)
        throw new HttpException(
                "Expected HTTP 200, but got a " + statusCode + ": " + statusLine.getReasonPhrase());

    HttpEntity responseEntity = response.getEntity();
    InputStream in = responseEntity.getContent();

    // now the Jena part
    ResultSet results = ResultSetFactory.fromXML(in);
    // also use Jena for getting the prefixes...
    Query query = QueryFactory.create(queryString);
    PrefixMapping prefixMap = query.getPrefixMapping();
    table = convertIntoTable(prefixMap, results);

    in.close();
    return table;
}

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 {//ww w  . j  a  v a  2 s.  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:org.jets3t.service.utils.RestUtils.java

public static HttpClient initHttpsConnection(final JetS3tRequestAuthorizer requestAuthorizer,
        Jets3tProperties jets3tProperties, String userAgentDescription,
        CredentialsProvider credentialsProvider) {
    // Configure HttpClient properties based on Jets3t Properties.
    HttpParams params = createDefaultHttpParams();
    params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties);

    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty(
            ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName()));

    HttpConnectionParams.setConnectionTimeout(params,
            jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000));
    HttpConnectionParams.setSoTimeout(params,
            jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000));
    HttpConnectionParams.setStaleCheckingEnabled(params,
            jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true));

    // Connection properties to take advantage of S3 window scaling.
    if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) {
        HttpConnectionParams.setSocketBufferSize(params,
                jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0));
    }/*from   w w w .  j  a v  a  2  s  .  co m*/

    HttpConnectionParams.setTcpNoDelay(params, true);

    // Set user agent string.
    String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null);
    if (userAgent == null) {
        userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription);
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting user agent string: " + userAgent);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true);
    HttpProtocolParams.setUseExpectContinue(params, expectContinue);

    long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout",
            0);
    ConnManagerParams.setTimeout(params, connectionManagerTimeout);

    DefaultHttpClient httpClient = wrapClient(params);
    httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler(
            jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer));

    if (credentialsProvider != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName());
        }
        httpClient.setCredentialsProvider(credentialsProvider);
        if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) {
            // Add as the very first interceptor in the protocol chain
            httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0);
        }
    }
    return httpClient;
}

From source file:org.jets3t.service.utils.RestUtils.java

/**
 * Initialises, or re-initialises, the underlying HttpConnectionManager and
 * HttpClient objects a service will use to communicate with an AWS service.
 * If proxy settings are specified in this service's {@link Jets3tProperties} object,
 * these settings will also be passed on to the underlying objects.
 *//*from w ww.j  a v a2s . c o m*/
public static HttpClient initHttpConnection(final JetS3tRequestAuthorizer requestAuthorizer,
        Jets3tProperties jets3tProperties, String userAgentDescription,
        CredentialsProvider credentialsProvider) {
    // Configure HttpClient properties based on Jets3t Properties.
    HttpParams params = createDefaultHttpParams();
    params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties);

    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty(
            ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName()));

    HttpConnectionParams.setConnectionTimeout(params,
            jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000));
    HttpConnectionParams.setSoTimeout(params,
            jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000));
    HttpConnectionParams.setStaleCheckingEnabled(params,
            jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true));

    // Connection properties to take advantage of S3 window scaling.
    if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) {
        HttpConnectionParams.setSocketBufferSize(params,
                jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0));
    }

    HttpConnectionParams.setTcpNoDelay(params, true);

    // Set user agent string.
    String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null);
    if (userAgent == null) {
        userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription);
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting user agent string: " + userAgent);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true);
    HttpProtocolParams.setUseExpectContinue(params, expectContinue);

    long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout",
            0);
    ConnManagerParams.setTimeout(params, connectionManagerTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler(
            jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer));

    if (credentialsProvider != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName());
        }
        httpClient.setCredentialsProvider(credentialsProvider);
        if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) {
            // Add as the very first interceptor in the protocol chain
            httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0);
        }
    }

    return httpClient;
}

From source file:com.icoin.trading.bitcoin.client.BitcoinClientDefaultConfig.java

private HttpClient httpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setCredentialsProvider(credentialsProvicer());
    return httpClient;
}

From source file:org.modeshape.test.kit.JBossASKitTest.java

@Test
public void webApplicationsShouldBeAccessible() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.setCredentialsProvider(new BasicCredentialsProvider() {
        @Override//  w  ww.  j ava  2 s .c  o  m
        public Credentials getCredentials(AuthScope authscope) {
            //defined via modeshape-user and modeshape-roles
            return new UsernamePasswordCredentials("admin", "admin");
        }
    });
    assertURIisAccessible("http://localhost:8080/modeshape-webdav", httpClient);
    assertURIisAccessible("http://localhost:8080/modeshape-rest", httpClient);
    assertURIisAccessible("http://localhost:8080/modeshape-cmis", httpClient);
}