4

I have searched a LOT for this and could not find a decent solution. The one using credentials provider is bad as it make double the amount of calls opposed to what is required i.e. it fires the request , gets a 401 and only then fires the request with the web auth credentials.

Anyone who has used android's httpclient library to do http post requests to a URL behind web auth successfully??

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Nitin
  • 1,451
  • 13
  • 17

1 Answers1

5

For HttpClient 4.0.x you use a HttpRequestInterceptor to enable preemptive authentication - since the AndroidHttpClient class doesn't expose the addRequestInterceptor(..) method you're probably going to have to use the DefaultHttpClient class.

This example will spam user1/user1 to any server interested. Adjust the AuthScope if you care even one bit about security.

DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1"));
client.addRequestInterceptor(new HttpRequestInterceptor() {
    public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
        AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
        if (state.getAuthScheme() == null) {
            BasicScheme scheme = new BasicScheme();
            CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
            Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY);
            if (credentials == null) {
                throw new HttpException();
            }
            state.setAuthScope(AuthScope.ANY);
            state.setAuthScheme(scheme);
            state.setCredentials(credentials);
        }
    }
}, 0); // 0 = first, and you really want to be first.
Jens
  • 16,853
  • 4
  • 55
  • 52
  • Thanx a ton , will try this out .. found the same thing on http://dlinsin.blogspot.com/2009/08/http-basic-authentication-with-android.html but I must have done something wrong . And what does that flag 0 stand for , didnt really get it – Nitin Sep 30 '11 at 10:08
  • 0 is the position of the request interceptor, i.e. 0 is first and it will process the request first. – Jens Sep 30 '11 at 10:18
  • @Nitin is this solution given by Jeans & on this link http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html working for you? I am also facing same problem of 401 Unauthorized. – Mobile Tech. Aug 09 '12 at 10:38