Example usage for org.apache.http.auth AuthState getAuthScheme

List of usage examples for org.apache.http.auth AuthState getAuthScheme

Introduction

In this page you can find the example usage for org.apache.http.auth AuthState getAuthScheme.

Prototype

public AuthScheme getAuthScheme() 

Source Link

Document

Returns actual AuthScheme .

Usage

From source file:com.xinlan.otma.net.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   w  ww .j av a 2 s  .c  om*/
 * 
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            } // end for
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                } // end for
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        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);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from w  w  w  . j  a  va2s .co m*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        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);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from  w w w.jav  a  2  s. c o m
 *
 * @param schemeRegistry
 *            SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, connectTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, responseTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ClientConnectionManager cm = createConnectionManager(schemeRegistry, httpParams);
    Utils.asserts(cm != null,
            "Custom implementation of #createConnectionManager(SchemeRegistry, BasicHttpParams) returned null");

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    // remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        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);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:org.apache.http.client.protocol.RequestAuthenticationBase.java

void process(final AuthState authState, final HttpRequest request, final HttpContext context) {
    AuthScheme authScheme = authState.getAuthScheme();
    Credentials creds = authState.getCredentials();
    switch (authState.getState()) {
    case FAILURE:
        return;//from  ww  w .j  a  v a 2  s  .co  m
    case SUCCESS:
        ensureAuthScheme(authScheme);
        if (authScheme.isConnectionBased()) {
            return;
        }
        break;
    case CHALLENGED:
        final Queue<AuthOption> authOptions = authState.getAuthOptions();
        if (authOptions != null) {
            while (!authOptions.isEmpty()) {
                final AuthOption authOption = authOptions.remove();
                authScheme = authOption.getAuthScheme();
                creds = authOption.getCredentials();
                authState.update(authScheme, creds);
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Generating response to an authentication challenge using "
                            + authScheme.getSchemeName() + " scheme");
                }
                try {
                    final Header header = authenticate(authScheme, creds, request, context);
                    request.addHeader(header);
                    break;
                } catch (final AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn(authScheme + " authentication error: " + ex.getMessage());
                    }
                }
            }
            return;
        } else {
            ensureAuthScheme(authScheme);
        }
    }
    if (authScheme != null) {
        try {
            final Header header = authenticate(authScheme, creds, request, context);
            request.addHeader(header);
        } catch (final AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error(authScheme + " authentication error: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.RequestProxyAuthentication.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }/*from  www . j av  a2 s. c o  m*/
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (authState == null) {
        return;
    }

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        return;
    }

    Credentials creds = authState.getCredentials();
    if (creds == null) {
        this.log.debug("User credentials not available");
        return;
    }
    if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
        try {
            request.addHeader(authScheme.authenticate(creds, request));
        } catch (AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error("Proxy authentication error: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.RequestTargetAuthentication.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }//from   www.ja  va 2s .c  om
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (authState == null) {
        return;
    }

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        return;
    }

    Credentials creds = authState.getCredentials();
    if (creds == null) {
        this.log.debug("User credentials not available");
        return;
    }

    if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
        try {
            request.addHeader(authScheme.authenticate(creds, request));
        } catch (AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error("Authentication error: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.ResponseAuthCache.java

public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    Args.notNull(response, "HTTP request");
    Args.notNull(context, "HTTP context");
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);

    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (target != null && targetState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Target auth state: " + targetState.getState());
        }// w  ww  .  j  a  v a 2  s  .  c om
        if (isCachable(targetState)) {
            final SchemeRegistry schemeRegistry = (SchemeRegistry) context
                    .getAttribute(ClientContext.SCHEME_REGISTRY);
            if (target.getPort() < 0) {
                final Scheme scheme = schemeRegistry.getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()),
                        target.getSchemeName());
            }
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (targetState.getState()) {
            case CHALLENGED:
                cache(authCache, target, targetState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, target, targetState.getAuthScheme());
            }
        }
    }

    final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
    final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (proxy != null && proxyState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Proxy auth state: " + proxyState.getState());
        }
        if (isCachable(proxyState)) {
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (proxyState.getState()) {
            case CHALLENGED:
                cache(authCache, proxy, proxyState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, proxy, proxyState.getAuthScheme());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.ResponseAuthCache.java

private boolean isCachable(final AuthState authState) {
    final AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null || !authScheme.isComplete()) {
        return false;
    }//from   w  ww .j  ava2s  .  c o  m
    final String schemeName = authScheme.getSchemeName();
    return schemeName.equalsIgnoreCase(AuthPolicy.BASIC) || schemeName.equalsIgnoreCase(AuthPolicy.DIGEST);
}

From source file:org.apache.http.impl.auth.HttpAuthenticator.java

public boolean isAuthenticationRequested(final HttpHost host, final HttpResponse response,
        final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) {
    if (authStrategy.isAuthenticationRequested(host, response, context)) {
        this.log.debug("Authentication required");
        if (authState.getState() == AuthProtocolState.SUCCESS) {
            authStrategy.authFailed(host, authState.getAuthScheme(), context);
        }// ww  w  .  j a v  a2 s  .c  om
        return true;
    } else {
        switch (authState.getState()) {
        case CHALLENGED:
        case HANDSHAKE:
            this.log.debug("Authentication succeeded");
            authState.setState(AuthProtocolState.SUCCESS);
            authStrategy.authSucceeded(host, authState.getAuthScheme(), context);
            break;
        case SUCCESS:
            break;
        default:
            authState.setState(AuthProtocolState.UNCHALLENGED);
        }
        return false;
    }
}

From source file:org.apache.http.impl.auth.HttpAuthenticator.java

public boolean handleAuthChallenge(final HttpHost host, final HttpResponse response,
        final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) {
    try {//from  w  ww  . ja va2 s  . c om
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        final AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                final String id = authScheme.getSchemeName();
                final Header challenge = challenges.get(id.toLowerCase(Locale.US));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (final MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " + ex.getMessage());
        }
        authState.reset();
        return false;
    }
}