How to use AndroidHttpClient (API level 8) and UsernamePasswordCredentials?

I am currently using DefaultHttpClient with ThreadSafeClientConnManager. This works fine, but I would like to replace this using AndroidHttpClient. Unfortunately, I cannot add UsernamePasswordCredentials, which is currently important to me. Can someone provide a hint or solution?

+5
source share
3 answers

For authentication you need to use a class HttpRequestInterceptor.

Here is an example

HttpRequestInterceptor httpRequestInterceptor = new HttpRequestInterceptor() {
    public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
        AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

        if (authState.getAuthScheme() == null) {
            AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
            Credentials creds = credsProvider.getCredentials(authScope);
            if (creds != null) {
                authState.setAuthScheme(new BasicScheme());
                authState.setCredentials(creds);
            }
        }
    }    
};
0
source

, , , - ( ), HttpGet. :

httpGet.addHeader("Authorization", "Basic " + Base64.encode(username+":"+password));
0

Some improvement for Saad Farooq is responding, the following code works for me.

final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");

getRequest = new HttpGet(url);

getRequest.addHeader("Authorization", "Basic " + Base64.encodeToString(new
                String(username + ":" + password).getBytes(), Base64.NO_WRAP));
0
source

All Articles