Example usage for org.apache.http.client.protocol ClientContext PROXY_AUTH_STATE

List of usage examples for org.apache.http.client.protocol ClientContext PROXY_AUTH_STATE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext PROXY_AUTH_STATE.

Prototype

String PROXY_AUTH_STATE

To view the source code for org.apache.http.client.protocol ClientContext PROXY_AUTH_STATE.

Click Source Link

Document

Attribute name of a org.apache.http.auth.AuthState object that represents the actual proxy authentication state.

Usage

From source file:httpclient.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Create local execution context
    HttpContext localContext = new BasicHttpContext();

    HttpGet httpget = new HttpGet("http://localhost/test");

    boolean trying = true;
    while (trying) {
        System.out.println("executing request " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget, localContext);

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        // Consume response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();/*from  w ww  . j a v a 2 s  .c  o m*/
        }

        int sc = response.getStatusLine().getStatusCode();

        AuthState authState = null;
        if (sc == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }

        if (authState != null) {
            System.out.println("----------------------------------------");
            AuthScope authScope = authState.getAuthScope();
            System.out.println("Please provide credentials");
            System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
            System.out.println(" Realm: " + authScope.getRealm());

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter username: ");
            String user = console.readLine();
            System.out.print("Enter password: ");
            String password = console.readLine();

            if (user != null && user.length() > 0) {
                Credentials creds = new UsernamePasswordCredentials(user, password);
                httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {// www.j  av  a  2s.c o  m
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*from w  w  w .  jav  a 2  s. com*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {//from  w  w  w.ja  v  a 2  s  . com
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:com.unboundid.scim.sdk.PreemptiveAuthInterceptor.java

/**
 * {@inheritDoc}/*from w  ww  .j a va2  s . c o  m*/
 */
@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (target.getPort() < 0) {
        SchemeRegistry schemeRegistry = (SchemeRegistry) context.getAttribute(ClientContext.SCHEME_REGISTRY);
        Scheme scheme = schemeRegistry.getScheme(target);
        target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()),
                target.getSchemeName());
    }

    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null) {
        authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        return;
    }

    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        return;
    }

    final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (targetState != null && targetState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(target);
        if (authScheme != null) {
            doPreemptiveAuth(target, authScheme, targetState, credsProvider);
        }
    }

    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 && proxyState.getState() == AuthProtocolState.UNCHALLENGED) {
        final AuthScheme authScheme = authCache.get(proxy);
        if (authScheme != null) {
            doPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
        }
    }
}

From source file:com.android.sdklib.internal.repository.UrlOpener.java

private static InputStream openWithHttpClient(String url, ITaskMonitor monitor)
        throws IOException, ClientProtocolException, CanceledByUserException {
    UserCredentials result = null;// www .  ja  v  a  2 s .c o m
    String realm = null;

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient();

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    HttpGet httpget = new HttpGet(url);

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpget, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.

                return new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        super.close();

                        // since Http Client is no longer needed, close it
                        httpClient.getConnectionManager().shutdown();
                    }
                };
            }
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java

public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException {
    // Create the POST request
    HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Add the POST parameters
    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
    //// w  w  w. j  av a 2 s  . com
    httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    //
    NotificationRegistry.getInstance().addNotification(uid, this);
    int tries = 0;
    AuthState authState = null;
    //
    while (tries < 2) {
        tries++;
        HttpResponse response = null;
        try {
            // Execute the POST request
            response = httpclient.execute(httpPost, localContext);
            //
            int sc = response.getStatusLine().getStatusCode();
            //
            if (sc == HttpStatus.SC_OK) {
                logger.debug(new StringBuilder().append("Wants to consume the structure packet from ")
                        .append(initParams.getRemoteContactPoint()));
                structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent());
                logger.debug("Connection established for: " + initParams.getRemoteContactPoint());
                break;
            } else {
                if (sc == HttpStatus.SC_UNAUTHORIZED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required
                else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
                else {
                    logger.error(new StringBuilder().append("Unexpected POST status code returned: ").append(sc)
                            .append("\nreason: ").append(response.getStatusLine().getReasonPhrase()));
                }
                if (authState != null) {
                    if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) {
                        logger.error("A valid username/password required to connect to the remote host: "
                                + initParams.getRemoteContactPoint());
                    } else {

                        AuthScope authScope = authState.getAuthScope();
                        logger.warn(new StringBuilder().append("Setting Credentials for host: ")
                                .append(authScope.getHost()).append(":").append(authScope.getPort()));
                        Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(),
                                initParams.getPassword());
                        httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                    }
                }
            }
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            logger.warn("Aborting the HTTP POST request.");
            httpPost.abort();
            throw ex;
        } finally {
            if (response != null && response.getEntity() != null) {
                response.getEntity().consumeContent();
            }
        }
    }

    if (structure == null)
        throw new RuntimeException("Cannot connect to the remote host.");

    return structure;
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

public DataField[] connectToRemote() throws IOException, ClassNotFoundException {
    // Create the GET request
    HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    ///*  w  w  w . j  a  v  a 2  s .c o  m*/
    structure = null;
    int tries = 0;
    AuthState authState = null;
    //
    if (inputStream != null) {
        try {
            if (response != null && response.getEntity() != null) {
                response.getEntity().consumeContent();
            }
            inputStream.close();
            inputStream = null;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
        }
    }
    //
    while (tries < 2) {
        tries++;
        try {
            // Execute the GET request
            response = httpclient.execute(httpget, localContext);
            //
            int sc = response.getStatusLine().getStatusCode();
            //
            if (sc == HttpStatus.SC_OK) {
                logger.debug(new StringBuilder().append("Wants to consume the structure packet from ")
                        .append(initParams.getRemoteContactPoint()));
                inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent());
                structure = (DataField[]) inputStream.readObject();
                logger.warn("Connection established for: " + initParams.getRemoteContactPoint());
                break;
            } else {
                if (sc == HttpStatus.SC_UNAUTHORIZED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required
                else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
                else {
                    logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc)
                            .append("\nreason: ").append(response.getStatusLine().getReasonPhrase()));
                }
                if (authState != null) {
                    if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) {
                        logger.error("A valid username/password required to connect to the remote host: "
                                + initParams.getRemoteContactPoint());
                    } else {

                        AuthScope authScope = authState.getAuthScope();
                        logger.warn(new StringBuilder().append("Setting Credentials for host: ")
                                .append(authScope.getHost()).append(":").append(authScope.getPort()));
                        Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(),
                                initParams.getPassword());
                        httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                    }
                }
            }
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            logger.warn("Aborting the HTTP GET request.");
            httpget.abort();
            throw ex;
        } finally {
            if (structure == null) {
                if (response != null && response.getEntity() != null) {
                    response.getEntity().consumeContent();
                }
            }
        }
    }

    if (structure == null)
        throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint());

    return structure;
}

From source file:gsn.http.rest.RestRemoteWrapper.java

public DataField[] connectToRemote() throws IOException, ClassNotFoundException {
    // Create the GET request
    HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
    // Create local execution context
    HttpContext localContext = new BasicHttpContext();
    ///* w ww .j  ava 2s.  co m*/
    structure = null;
    int tries = 0;
    AuthState authState = null;
    //
    if (inputStream != null) {
        try {
            if (response != null && response.getEntity() != null) {
                response.getEntity().consumeContent();
            }
            inputStream.close();
            inputStream = null;
        } catch (Exception e) {
            logger.debug(e.getMessage(), e);
        }
    }
    //
    while (tries < 2) {
        tries++;
        try {
            // Execute the GET request
            response = httpclient.execute(httpget, localContext);
            //
            int sc = response.getStatusLine().getStatusCode();
            //
            if (sc == HttpStatus.SC_OK) {
                logger.debug(new StringBuilder().append("Wants to consume the structure packet from ")
                        .append(initParams.getRemoteContactPoint()).toString());
                inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent());
                structure = (DataField[]) inputStream.readObject();
                logger.warn("Connection established for: " + initParams.getRemoteContactPoint());
                break;
            } else {
                if (sc == HttpStatus.SC_UNAUTHORIZED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required
                else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
                    authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required
                else {
                    logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc)
                            .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())
                            .toString());
                }
                if (authState != null) {
                    if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) {
                        logger.error("A valid username/password required to connect to the remote host: "
                                + initParams.getRemoteContactPoint());
                    } else {

                        AuthScope authScope = authState.getAuthScope();
                        logger.warn(new StringBuilder().append("Setting Credentials for host: ")
                                .append(authScope.getHost()).append(":").append(authScope.getPort())
                                .toString());
                        Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(),
                                initParams.getPassword());
                        httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                    }
                }
            }
        } catch (RuntimeException ex) {
            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying
            // connection and release it back to the connection manager.
            logger.warn("Aborting the HTTP GET request.");
            httpget.abort();
            throw ex;
        } finally {
            if (structure == null) {
                if (response != null && response.getEntity() != null) {
                    response.getEntity().consumeContent();
                }
            }
        }
    }

    if (structure == null)
        throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint());

    return structure;
}

From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java

public void connect() throws IOException {
    if (!connected) {
        final String userInfo = url.getUserInfo();
        final boolean isAuthenticationRequestedWithUsername = username != null && !username.equals("");

        // Create the HTTP client and HTTP context for the client (we expect this to be fairly lightweight)
        final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
        final HttpContext httpContext = new BasicHttpContext();

        // Set cookie store, creating a new one if none was provided to us
        if (cookieStore == null)
            cookieStore = new BasicCookieStore();
        httpClient.setCookieStore(cookieStore);

        // Set proxy and host authentication
        if (proxyAuthState != null)
            httpContext.setAttribute(ClientContext.PROXY_AUTH_STATE, proxyAuthState);
        if (userInfo != null || isAuthenticationRequestedWithUsername) {

            // Make authentication preemptive; interceptor is added first, as the Authentication header is added
            // by HttpClient's RequestTargetAuthentication which is itself an interceptor, so our interceptor
            // needs to run before RequestTargetAuthentication, otherwise RequestTargetAuthentication won't find
            // the appropriate AuthState/AuthScheme/Credentials in the HttpContext

            // Don't add the interceptor if we don't want preemptive authentication!
            if (!"false".equals(preemptiveAuthentication)) {
                httpClient.addRequestInterceptor(preemptiveAuthHttpRequestInterceptor, 0);
            }/*from ww  w. ja  v a 2 s . c om*/

            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
            final AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            final Credentials credentials;
            if (userInfo != null) {
                // Set username and optional password specified on URL
                final int separatorPosition = userInfo.indexOf(":");
                String username = separatorPosition == -1 ? userInfo : userInfo.substring(0, separatorPosition);
                String password = separatorPosition == -1 ? "" : userInfo.substring(separatorPosition + 1);
                // If the username/password contain special character, those character will be encoded, since we
                // are getting this from a URL. Now do the decoding.
                username = URLDecoder.decode(username, "utf-8");
                password = URLDecoder.decode(password, "utf-8");
                credentials = new UsernamePasswordCredentials(username, password);
            } else {
                // Set username and password specified externally
                credentials = domain == null
                        ? new UsernamePasswordCredentials(username, password == null ? "" : password)
                        : new NTCredentials(username, password, url.getHost(), domain);
            }
            credentialsProvider.setCredentials(authScope, credentials);
        }

        // If method has not been set, use GET
        // This can happen e.g. when this connection handler is used from URLFactory
        if (method == null)
            setRequestMethod("GET");

        // Set all headers,
        final boolean skipAuthorizationHeader = userInfo != null || username != null;
        for (final Map.Entry<String, String[]> currentEntry : requestProperties.entrySet()) {
            final String currentHeaderName = currentEntry.getKey();
            final String[] currentHeaderValues = currentEntry.getValue();
            for (final String currentHeaderValue : currentHeaderValues) {
                // Skip over Authorization header if user authentication specified
                if (skipAuthorizationHeader && currentHeaderName.toLowerCase()
                        .equals(Connection.AUTHORIZATION_HEADER.toLowerCase()))
                    continue;
                method.addHeader(currentHeaderName, currentHeaderValue);
            }
        }

        // Create request entity with body
        if (method instanceof HttpEntityEnclosingRequest) {

            // Use the body that was set directly, or the result of writing to the OutputStream
            final byte[] body = (requestBody != null) ? requestBody : (os != null) ? os.toByteArray() : null;

            if (body != null) {
                final Header contentTypeHeader = method.getFirstHeader("Content-Type"); // Header names are case-insensitive for comparison
                if (contentTypeHeader == null)
                    throw new ProtocolException("Can't set request entity: Content-Type header is missing");
                final ByteArrayEntity byteArrayEntity = new ByteArrayEntity(body);
                byteArrayEntity.setContentType(contentTypeHeader);
                ((HttpEntityEnclosingRequest) method).setEntity(byteArrayEntity);
            }
        }

        // Make request
        httpResponse = httpClient.execute(method, httpContext);
        connected = true;
    }
}