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:net.gromgull.android.bibsonomyposter.BibsonomyPosterActivity.java

public void bookmark(String url, String title) throws ClientProtocolException, IOException {
    CredentialsProvider credProvider = new BasicCredentialsProvider();

    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,

            AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, apikey));

    StringWriter sw = new StringWriter();

    XmlSerializer x = Xml.newSerializer();
    x.setOutput(sw);//  w w w.  ja v  a 2 s  . c  om
    x.startDocument(null, null);
    x.startTag(null, "bibsonomy");
    x.startTag(null, "post");
    x.attribute(null, "description", "a bookmark");

    x.startTag(null, "user");
    x.attribute(null, "name", username);
    x.endTag(null, "user");

    x.startTag(null, "tag");
    x.attribute(null, "name", "from_android");
    x.endTag(null, "tag");

    x.startTag(null, "group");
    x.attribute(null, "name", "public");
    x.endTag(null, "group");

    x.startTag(null, "bookmark");
    x.attribute(null, "url", url);
    x.attribute(null, "title", title);
    x.endTag(null, "bookmark");

    x.endTag(null, "post");
    x.endTag(null, "bibsonomy");

    x.endDocument();

    Log.v(LOGTAG, "XML: " + sw.toString());

    HttpPost httppost = new HttpPost("http://www.bibsonomy.org/api/users/" + username + "/posts");
    StringEntity e = new StringEntity(sw.toString());
    e.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/xml"));
    httppost.setEntity(e);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCredentialsProvider(credProvider);
    HttpResponse response = httpclient.execute(httppost);
    Log.i(LOGTAG, "Bibsonomy said :" + response.getStatusLine());
    if (response.getStatusLine().getStatusCode() != 201) {
        HttpEntity re = response.getEntity();
        byte b[] = new byte[(int) re.getContentLength()];
        re.getContent().read(b);
        Log.v(LOGTAG, "Bibsonomy said: " + new String(b));
        throw new IOException("Bibsonomy said :" + response.getStatusLine());

    }
}

From source file:ua.pp.msk.cliqr.PostProcessorImpl.java

private void init(URL url, String user, String password) throws ClientSslException {
    this.targetUrl = url;
    HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());

    BasicAuthCache aCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme(ChallengeState.TARGET);
    aCache.put(htHost, basicAuth);/*from   w ww  . jav  a2 s.  c  o  m*/

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
    BasicCredentialsProvider cProvider = new BasicCredentialsProvider();
    cProvider.setCredentials(new AuthScope(htHost), creds);
    logger.debug("Credential provider: " + cProvider.toString());

    context = new BasicHttpContext();
    ClientContextConfigurer cliCon = new ClientContextConfigurer(context);
    context.setAttribute(ClientContext.AUTH_CACHE, aCache);
    //context.setAuthCache(aCache);
    cliCon.setCredentialsProvider(cProvider);
    //context.setCredentialsProvider(cProvider);
    SSLSocketFactory sslSocketFactory = null;
    try {
        //SSLContext trustySslContext = SSLContextBuilder.create().loadTrustMaterial( new TrustSelfSignedStrategy()).build();
        //sslConnectionSocketFactory = new SSLConnectionSocketFactory(trustySslContext, new CliQrHostnameVerifier());
        sslSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new CliQrHostnameVerifier());
    } catch (KeyManagementException ex) {
        logger.error("Cannot manage secure keys", ex);
        throw new ClientSslException("Cannot manage secure keys", ex);
    } catch (KeyStoreException ex) {
        logger.error("Cannot build SSL context due to KeyStore error", ex);
        throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex);
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Unsupported security algorithm", ex);
        throw new ClientSslException("Unsupported security algorithm", ex);
    } catch (UnrecoverableKeyException ex) {
        logger.error("Unrecoverable key", ex);
        throw new ClientSslException("Unrecoverrable key", ex);
    }

    DefaultHttpClient defClient = new DefaultHttpClient();
    defClient.setRedirectStrategy(new CliQrRedirectStrategy());
    defClient.setCredentialsProvider(cProvider);
    Scheme https = new Scheme("https", 443, sslSocketFactory);
    defClient.getConnectionManager().getSchemeRegistry().register(https);
    defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy());
    client = defClient;
}

From source file:de.azapps.mirakel.sync.Network.java

private String downloadUrl(String myurl) throws IOException, URISyntaxException {
    if (token != null) {
        myurl += "?authentication_key=" + token;
    }/*from   w w w .j a v a2  s  . c  o  m*/
    if (myurl.indexOf("https") == -1) {
        Integer[] t = { NoHTTPS };
        publishProgress(t);
    }

    /*
     * String authorizationString = null;
     * if (syncTyp == ACCOUNT_TYPES.CALDAV) {
     * authorizationString = "Basic "
     * + Base64.encodeToString(
     * (username + ":" + password).getBytes(),
     * Base64.NO_WRAP);
     * }
     */

    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(new AuthScope(new URI(myurl).getHost(), -1),
            new UsernamePasswordCredentials(username, password));

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpClient httpClient;
    /*
     * if(syncTyp == ACCOUNT_TYPES.MIRAKEL)
     * httpClient = sslClient(client);
     * else {
     */
    DefaultHttpClient tmpHttpClient = new DefaultHttpClient(params);
    tmpHttpClient.setCredentialsProvider(credentials);

    httpClient = tmpHttpClient;
    // }
    httpClient.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);

    HttpResponse response;
    try {
        switch (mode) {
        case GET:
            Log.v(TAG, "GET " + myurl);
            HttpGet get = new HttpGet();
            get.setURI(new URI(myurl));
            response = httpClient.execute(get);
            break;
        case PUT:
            Log.v(TAG, "PUT " + myurl);
            HttpPut put = new HttpPut();
            if (syncTyp == ACCOUNT_TYPES.CALDAV) {
                put.addHeader(HTTP.CONTENT_TYPE, "text/calendar; charset=utf-8");
            }
            put.setURI(new URI(myurl));
            put.setEntity(new StringEntity(content, HTTP.UTF_8));
            Log.v(TAG, content);

            response = httpClient.execute(put);
            break;
        case POST:
            Log.v(TAG, "POST " + myurl);
            HttpPost post = new HttpPost();
            post.setURI(new URI(myurl));
            post.setEntity(new UrlEncodedFormEntity(headerData, HTTP.UTF_8));
            response = httpClient.execute(post);
            break;
        case DELETE:
            Log.v(TAG, "DELETE " + myurl);
            HttpDelete delete = new HttpDelete();
            delete.setURI(new URI(myurl));
            response = httpClient.execute(delete);
            break;
        case REPORT:
            Log.v(TAG, "REPORT " + myurl);
            HttpReport report = new HttpReport();
            report.setURI(new URI(myurl));
            Log.d(TAG, content);
            report.setEntity(new StringEntity(content, HTTP.UTF_8));
            response = httpClient.execute(report);
            break;
        default:
            Log.wtf("HTTP-MODE", "Unknown Http-Mode");
            return null;
        }
    } catch (Exception e) {
        Log.e(TAG, "No Networkconnection available");
        Log.w(TAG, Log.getStackTraceString(e));
        return "";
    }
    Log.v(TAG, "Http-Status: " + response.getStatusLine().getStatusCode());
    if (response.getEntity() == null)
        return "";
    String r = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
    Log.d(TAG, r);
    return r;
}

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:org.energyos.espi.thirdparty.web.ClientRestTemplate.java

public ClientRestTemplate(String username, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    httpClient.setCredentialsProvider(credentialsProvider);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    this.setRequestFactory(rf);
}

From source file:org.springframework.mobile.urbanairship.impl.UrbanAirshipTemplate.java

private RestTemplate createRestTemplate(String key, String secret) {
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(key, secret));
    httpClient.setCredentialsProvider(credentialsProvider);
    requestFactory.setHttpClient(httpClient);
    return new RestTemplate(requestFactory);
}

From source file:com.nesscomputing.tinyhttp.HttpFetcher.java

public <T> T get(final URI uri, final String login, final String pw, final HttpContentConverter<T> converter)
        throws IOException {
    final HttpRequestBase httpRequest = new HttpGet(uri);
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params);
    // Maximum of three retries...
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false));

    if (login != null) {
        httpClient.setCredentialsProvider(new HttpFetcherCredentialsProvider(login, pw));
    }//from w w  w . j a  va2  s  .c o  m

    final HttpContentResponseHandler<T> responseHandler = new HttpContentResponseHandler<T>(converter);

    try {
        final HttpContext httpContext = new BasicHttpContext();
        final HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);

        try {
            return responseHandler.handle(httpRequest, httpResponse);
        } finally {
            // Make sure that the content has definitely been consumed. Otherwise,
            // keep-alive does not work.
            final HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                Closeables.closeQuietly(entity.getContent());
            }
        }
    } catch (Exception e) {
        LOG.warn("Aborting Request!", e);

        httpRequest.abort();
        throw Throwables.propagate(e);
    }
}

From source file:org.springframework.data.solr.server.support.SolrClientUtilTests.java

/**
 * @see DATASOLR-189/*from   www .  j  a  va2  s. co m*/
 */
@Test
public void cloningLBHttpSolrClientShouldCopyCredentialsProviderCorrectly() {

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar"));

    DefaultHttpClient client = new DefaultHttpClient();
    client.setCredentialsProvider(credentialsProvider);

    LBHttpSolrClient lbSolrClient = new LBHttpSolrClient(client, BASE_URL, ALTERNATE_BASE_URL);

    LBHttpSolrClient cloned = SolrClientUtils.clone(lbSolrClient, CORE_NAME);
    Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(),
            IsEqual.<CredentialsProvider>equalTo(credentialsProvider));
}

From source file:org.springframework.data.solr.server.support.SolrClientUtilTests.java

/**
 * @see DATASOLR-189/*from   w  w w. ja v  a2s.  com*/
 */
@Test
public void cloningHttpSolrClientShouldCopyCredentialsProviderCorrectly() {

    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("foo", "bar"));

    DefaultHttpClient client = new DefaultHttpClient();
    client.setCredentialsProvider(credentialsProvider);

    HttpSolrClient solrClient = new HttpSolrClient(BASE_URL, client);
    HttpSolrClient cloned = SolrClientUtils.clone(solrClient);

    Assert.assertThat(((AbstractHttpClient) cloned.getHttpClient()).getCredentialsProvider(),
            IsEqual.<CredentialsProvider>equalTo(credentialsProvider));
}

From source file:me.willowcheng.makerthings.util.MjpegStreamer.java

public InputStream httpRequest(String url, String usr, String pwd) {
    HttpResponse res = null;//from  ww w  .jav a 2s. co  m
    DefaultHttpClient httpclient = new DefaultHttpClient();
    CredentialsProvider credProvider = new BasicCredentialsProvider();
    credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(usr, pwd));
    httpclient.setCredentialsProvider(credProvider);
    Log.d(TAG, "1. Sending http request");
    try {
        res = httpclient.execute(new HttpGet(URI.create(url)));
        Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode());
        if (res.getStatusLine().getStatusCode() == 401) {
            //You must turn off camera User Access Control before this will work
            return null;
        }
        Log.d(TAG, "content-type = " + res.getEntity().getContentType());
        Log.d(TAG, "content-encoding = " + res.getEntity().getContentEncoding());
        return res.getEntity().getContent();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        Log.d(TAG, "Request failed-ClientProtocolException", e);
        //Error connecting to camera
    } catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "Request failed-IOException", e);
        //Error connecting to camera
    }

    return null;

}