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:com.norconex.collector.http.client.impl.DefaultHttpClientInitializer.java

protected void setupBasicDigestAuth(DefaultHttpClient httpClient) {

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getAuthUsername(), getAuthPassword());
    AuthScope authscope = new AuthScope(getAuthHostname(), getAuthPort(), getAuthRealm(), getAuthMethod());

    httpClient.getCredentialsProvider().setCredentials(authscope, creds);
}

From source file:org.uoyabause.android.AsyncDownload.java

private Integer sendReport(String uri, String product_id) {

    Log.d("sendReport", "================ sendReport start ================");

    mainActivity._report_status = Yabause.REPORT_STATE_FAIL_CONNECTION;

    DefaultHttpClient client = new DefaultHttpClient();
    try {//w  ww . java2  s.c  om
        Credentials credentials = new UsernamePasswordCredentials(mainActivity.getString(R.string.basic_user),
                mainActivity.getString(R.string.basic_password));
        AuthScope scope = new AuthScope(null, -1);
        client.getCredentialsProvider().setCredentials(scope, credentials);
    } catch (Exception e) {
        Log.d("sendReport", "error " + e.getMessage());
        e.printStackTrace();
        client.getConnectionManager().shutdown();
        return 0;
    }

    String device_id = Settings.Secure.getString(mainActivity.getContentResolver(), Settings.Secure.ANDROID_ID);
    try {
        long id = -1;
        Log.d("sendReport", "uri=" + uri + "games/" + product_id);
        HttpGet httpGet = new HttpGet(new URI(uri + "games/" + product_id));
        HttpResponse resp = client.execute(httpGet);
        int status = resp.getStatusLine().getStatusCode();
        Log.d("sendReport", "get status=" + status);
        if (HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get id respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    id = rootObject.getLong("id");
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
        } else {
        }
        if (id == -1) {

            HttpPost httpPost = new HttpPost(new URI(uri + "games/"));
            StringEntity se = new StringEntity(mainActivity.current_game_info.toString());
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            resp = client.execute(httpPost);
            status = resp.getStatusLine().getStatusCode();
            Log.d("sendReport", "post stats=" + status);
            if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
                try {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    resp.getEntity().writeTo(outputStream);
                    String data;
                    data = outputStream.toString(); // JSON
                    Log.d("sendReport", "post respose=" + data);
                    JSONObject rootObject = new JSONObject(data);
                    if (rootObject.getBoolean("result") == true) {
                        id = rootObject.getLong("id");
                    }
                } catch (Exception e) {
                    Log.d("sendReport", "error");
                    e.printStackTrace();
                }
            } else {
            }

        }
        Log.d("sendReport", "ID=" + id);
        if (id == -1) {
            client.getConnectionManager().shutdown();
            return -1;
        }

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mainActivity);
        String cputype = sharedPref.getString("pref_cpu", "2");
        String gputype = sharedPref.getString("pref_video", "1");
        JSONObject reportJson = new JSONObject();
        reportJson.put("rating", mainActivity.current_report._rating);
        if (mainActivity.current_report._message != null) {
            reportJson.put("message", mainActivity.current_report._message);
        }
        reportJson.put("emulator_version", Home.getVersionName(mainActivity));
        reportJson.put("device", android.os.Build.MODEL);
        reportJson.put("user_id", 1);
        reportJson.put("device_id", device_id);
        reportJson.put("game_id", id);
        reportJson.put("cpu_type", cputype);
        reportJson.put("video_type", gputype);
        JSONObject sendJson = new JSONObject();
        sendJson.put("report", reportJson);
        if (mainActivity.current_report._screenshot) {
            JSONObject jsonObjimg = new JSONObject();
            jsonObjimg.put("data", mainActivity.current_report._screenshot_base64);
            jsonObjimg.put("filename", mainActivity.current_report._screenshot_save_path);
            jsonObjimg.put("content_type", "image/png");
            JSONObject jsonObjgame = sendJson.getJSONObject("report");
            jsonObjgame.put("screenshot", jsonObjimg);
            File file = new File(mainActivity.current_report._screenshot_save_path);
            file.delete();
        }
        Log.d("sendReport", reportJson.toString());
        HttpPost httpPost = new HttpPost(new URI(uri + "reports/"));
        StringEntity se = new StringEntity(sendJson.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        resp = client.execute(httpPost);
        status = resp.getStatusLine().getStatusCode();
        if (HttpStatus.SC_CREATED == status || HttpStatus.SC_OK == status) {
            try {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resp.getEntity().writeTo(outputStream);
                String data;
                data = outputStream.toString(); // JSON
                JSONObject rootObject = new JSONObject(data);
                Log.d("sendReport", "get respose=" + data);
                if (rootObject.getBoolean("result") == true) {
                    mainActivity._report_status = Yabause.REPORT_STATE_SUCCESS;
                } else {
                    int return_code = rootObject.getInt("code");
                    mainActivity._report_status = return_code;
                }
            } catch (Exception e) {
                Log.d("sendReport", "error");
                e.printStackTrace();
            }
            client.getConnectionManager().shutdown();
            return 0;
        }
        client.getConnectionManager().shutdown();
        return -1;

    } catch (Exception e) {
        Log.d("sendReport", "error:" + e.getMessage());
        e.printStackTrace();
    } finally {
        client.getConnectionManager().shutdown();
    }
    return -1;
}

From source file:com.codebutler.rsp.Playlist.java

public void fetchItems(final FetchItemsProgressListener progressListener) throws Exception {
    if (mItems != null)
        throw new Exception("fetchItems() already called!");

    mItems = new SortedArrayList<Item>(new Comparator<Item>() {
        public int compare(Item first, Item second) {
            return first.getTitle().compareToIgnoreCase(second.getTitle());
        }//  www  .ja  v  a  2 s .c  om
    });

    mOrderedArtists = new SortedArrayList<Artist>(new Comparator<Artist>() {
        public int compare(Artist first, Artist second) {
            return first.getName().compareToIgnoreCase(second.getName());
        }
    });

    mArtists = new HashMap<String, Artist>();

    mAlbums = new SortedArrayList<Album>(new Comparator<Album>() {
        public int compare(Album first, Album second) {
            return first.getName().compareToIgnoreCase(second.getName());
        }
    });

    URL url = mServer.buildUrl("db/" + Integer.toString(mId));
    Log.d("FetchItems", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    String password = mServer.getPassword();
    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }

    HttpGet method = new HttpGet(url.toURI());

    InputStream stream = client.execute(method).getEntity().getContent();

    try {
        /*
         <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
         <response>
        <status>
            <errorcode>0</errorcode>
            <errorstring></errorstring>
            <records>0</records>
            <totalrecords>1</totalrecords>
        </status>
        <items>
            <item>
                <id>1</id>
                <title>Rock Robotic (Osx Mix)</title>
                <artist>Oscillator X</artist>
                <album>Techno * Techyes</album>
                <genre>Dance &amp; DJ</genre>
                <type>mp3</type>
                <bitrate>192</bitrate>
                <samplerate>44100</samplerate>
                <song_length>61440</song_length>
                <file_size>1474560</file_size>
                <year>0</year>
                <track>15</track>
                <total_tracks>0</total_tracks>
                <disc>0</disc>
                <total_discs>0</total_discs>
                <bpm>0</bpm>
                <compilation>0</compilation>
                <rating>0</rating>
                <play_count>4</play_count>
                <description>MPEG audio file</description>
                <time_added>1270096204</time_added>
                <time_modified>1270078936</time_modified>
                <time_played>1270156178</time_played>
                <disabled>0</disabled>
                <codectype>mpeg</codectype>
            </item>
        </items>
         </response>
         */

        RootElement rootElement = new RootElement("response");
        Element itemsElement = rootElement.getChild("items");
        Element itemElement = itemsElement.getChild("item");
        Element idElement = itemElement.getChild("id");
        Element titleElement = itemElement.getChild("title");
        Element artistElement = itemElement.getChild("artist");
        Element albumElement = itemElement.getChild("album");
        Element lengthElement = itemElement.getChild("song_length");

        itemElement.setElementListener(new ElementListener() {
            public void start(Attributes arg0) {
                mCurrentItem = new Item(Playlist.this);
            }

            public void end() {
                mItems.add(mCurrentItem);

                // Artist cache
                String artistName = mCurrentItem.getArtist();
                if (artistName != null && artistName.trim().length() > 0) {
                    Artist artist = mArtists.get(artistName);
                    if (artist == null) {
                        artist = new Artist(artistName);
                        mArtists.put(artistName, artist);
                        mOrderedArtists.add(artist);
                    }

                    // Album cache
                    // FIXME: This should support compilation albums!
                    String albumName = mCurrentItem.getAlbum();
                    if (albumName != null && albumName.trim().length() > 0) {
                        Album album = artist.getAlbum(albumName);
                        if (album == null) {
                            album = new Album(artist, albumName);
                            artist.addAlbum(album);
                            mAlbums.add(album);
                        }
                        album.addItem(mCurrentItem);
                    }
                }

                mCurrentItem = null;

                if (progressListener != null) {
                    if ((mItems.size() % 100) == 0)
                        progressListener.onProgressChange(mItems.size());
                }
            }
        });

        idElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setId(Integer.parseInt(body));
            }
        });

        titleElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setTitle(body);
            }
        });

        artistElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setArtist(body);
            }
        });

        albumElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setAlbum(body);
            }
        });

        lengthElement.setEndTextElementListener(new EndTextElementListener() {
            public void end(String body) {
                mCurrentItem.setDuration(Long.parseLong(body) / 1000);
            }
        });

        android.util.Xml.parse(stream, Xml.Encoding.UTF_8, rootElement.getContentHandler());
    } finally {
        stream.close();
    }
}

From source file:HybridIT.com.fourspaces.couchdb.Session.java

/**
* Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection
* This isn't supported by CouchDB - you need a proxy in front to use this
* @param host - hostname/*from ww w  .j  a  v a2 s . c o m*/
* @param port - port to use
* @param user - username
* @param pass - password
* @param secure  - use an SSL connection?
*/
public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {
    this.host = host;
    this.port = port;
    this.user = user;
    this.pass = pass;
    this.usesAuth = usesAuth;
    this.secure = secure;

    httpParams = new BasicHttpParams();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    DefaultHttpClient defaultClient = new DefaultHttpClient(connManager, httpParams);
    if (user != null) {
        defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pass));
    }

    this.httpClient = defaultClient;

    setUserAgent("couchdb4j");
    setSocketTimeout((30 * 1000));
    setConnectionTimeout((15 * 1000));

}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

private void configureAuthentication(final DefaultHttpClient httpclient, final String scheme,
        final Principal principal) {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, scheme),
            new Credentials() {
                public Principal getUserPrincipal() {
                    return principal;
                }// www .j a v  a2  s .  c om

                public String getPassword() {
                    return password;
                }
            });
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?/*from   w  w  w  .j av a 2 s .co  m*/
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}

From source file:li.klass.fhem.fhem.FHEMWEBConnection.java

private RequestResult<InputStream> executeRequest(String urlSuffix, DefaultHttpClient client, String command) {
    String url = null;/*from   w ww.jav  a2s.  c o m*/
    if (client == null) {
        client = createNewHTTPClient(getConnectionTimeoutMilliSeconds(), SOCKET_TIMEOUT);
    }
    try {
        HttpGet request = new HttpGet();
        request.addHeader("Accept-Encoding", "gzip");

        url = serverSpec.getUrl() + urlSuffix;

        Log.i(TAG, "accessing URL " + url);
        URI uri = new URI(url);

        client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(serverSpec.getUsername(), getPassword()));

        request.setURI(uri);

        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, "response status code is " + statusCode);

        RequestResult<InputStream> errorResult = handleHttpStatusCode(statusCode);
        if (errorResult != null) {
            String msg = "found error " + errorResult.error.getClass().getSimpleName() + " for "
                    + "status code " + statusCode;
            Log.d(TAG, msg);
            ErrorHolder.setError(null, msg);
            return errorResult;
        }

        InputStream contentStream = response.getEntity().getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");
        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
            contentStream = new GZIPInputStream(contentStream);
        }
        return new RequestResult<InputStream>(contentStream);
    } catch (ConnectTimeoutException e) {
        Log.i(TAG, "connection timed out", e);
        setErrorInErrorHolderFor(e, url, command);
        return new RequestResult<InputStream>(RequestResultError.CONNECTION_TIMEOUT);
    } catch (ClientProtocolException e) {
        String errorText = "cannot connect, invalid URL? (" + url + ")";
        setErrorInErrorHolderFor(e, url, command);
        ErrorHolder.setError(e, errorText);
        return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR);
    } catch (IOException e) {
        Log.i(TAG, "cannot connect to host", e);
        setErrorInErrorHolderFor(e, url, command);
        return new RequestResult<InputStream>(RequestResultError.HOST_CONNECTION_ERROR);
    } catch (URISyntaxException e) {
        Log.i(TAG, "invalid URL syntax", e);
        setErrorInErrorHolderFor(e, url, command);
        throw new IllegalStateException("cannot parse URL " + urlSuffix, e);
    }
}

From source file:census.couchdroid.CouchSession.java

/**
 * Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection
 * This isn't supported by CouchDB - you need a proxy in front to use this
 * @param host - hostname/*ww w .  j a  v a2  s .  c o m*/
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param secure  - use an SSL connection?
 */
public CouchSession(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {
    this.host = host;
    this.port = port;
    this.user = user;
    this.pass = pass;
    this.usesAuth = usesAuth;
    this.secure = secure;

    httpParams = new BasicHttpParams();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    DefaultHttpClient defaultClient = new DefaultHttpClient(connManager, httpParams);
    if (user != null) {
        defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(user, pass));
    }

    this.httpClient = defaultClient;

    setUserAgent("couchdb4j");
    setSocketTimeout((30 * 1000));
    setConnectionTimeout((15 * 1000));

}

From source file:com.glodon.paas.document.api.AbstractDocumentAPITest.java

private void setCredentials(DefaultHttpClient client, String host, int port, String userName, String password) {
    if (client != null) {
        AuthScope authScope = new AuthScope(host, port);
        Credentials credentials = new UsernamePasswordCredentials(userName, password);
        client.getCredentialsProvider().setCredentials(authScope, credentials);
    }/*from w  w w. ja  va  2s. c  om*/
}