Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext getAttribute.

Prototype

Object getAttribute(String str);

Source Link

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();/*w ww . j a  va 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 {/*from ww  w.j  a  v  a 2 s .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:yangqi.hc.HttpContextTest.java

private static void showAttr(String attrname, HttpContext context) {
    System.out.println(attrname + " : " + context.getAttribute(attrname));
}

From source file:com.gargoylesoftware.htmlunit.httpclient.SocksConnectionSocketFactory.java

static HttpHost getSocksProxy(final HttpContext context) {
    return (HttpHost) context.getAttribute(SOCKS_PROXY);
}

From source file:org.esigate.http.RedirectStrategy.java

public static HttpRequest getLastRequest(HttpRequest httpRequest, HttpContext httpContext) {
    HttpRequest lastRedirectionRequest = (HttpRequest) httpContext.getAttribute(LAST_REQUEST);
    if (lastRedirectionRequest != null) {
        return lastRedirectionRequest;
    }//from  w  w  w  .j a v  a 2  s .  c  o  m
    return httpRequest;
}

From source file:bad.robot.http.apache.ApacheAuthenticationSchemeHttpContextBuilderTest.java

private static AuthScheme schemeFromCacheByUrl(URL url, HttpContext context) {
    AuthCache cache = (AuthCache) context.getAttribute(AUTH_CACHE);
    return cache.get(asHttpHost(url));
}

From source file:ee.ria.xroad.proxy.serverproxy.CustomSSLSocketFactory.java

private static ServiceId getServiceId(HttpContext context) throws Exception {
    Object attribute = context.getAttribute(ServiceId.class.getName());
    if (attribute == null || !(attribute instanceof ServiceId)) {
        throw new Exception("Cannot get ServiceId from HttpContext");
    }//w ww  .  jav a  2 s.c  o  m

    return (ServiceId) attribute;
}

From source file:com.gooddata.http.client.CookieUtils.java

/**
 * Add (or replace) super-secure cookie in context.
 * @param sst super-secure token/*w  ww .  jav  a  2 s .c  o m*/
 * @param context HTTP context
 * @param domain domain
 * @throws GoodDataAuthException http client does not support cookie
 */
static void replaceSst(final String sst, final HttpContext context, final String domain) {
    notNull(context, "Context cannot be null.");
    final CookieStore cookieStore = (CookieStore) context.getAttribute(HttpClientContext.COOKIE_STORE);
    replaceSst(sst, cookieStore, domain);
}

From source file:com.netflix.spinnaker.orca.pipeline.util.HttpClientUtils.java

private static CloseableHttpClient httpClientWithServiceUnavailableRetryStrategy() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override/*from   www . ja  va 2  s  .  c  o m*/
                public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(HttpCoreContext.HTTP_REQUEST);
                    LOGGER.info("Response code {} for {}", statusCode, currentReq.getURI());

                    if (statusCode >= HttpStatus.SC_OK && statusCode <= 299) {
                        return false;
                    }

                    boolean shouldRetry = (statusCode == 429
                            || RETRYABLE_500_HTTP_STATUS_CODES.contains(statusCode))
                            && executionCount <= MAX_RETRIES;
                    if (!shouldRetry) {
                        throw new RetryRequestException(String.format("Not retrying %s. Count %d, Max %d",
                                currentReq.getURI(), executionCount, MAX_RETRIES));
                    }

                    LOGGER.error("Retrying request on response status {}. Count {} Max is {}", statusCode,
                            executionCount, MAX_RETRIES);
                    return true;
                }

                @Override
                public long getRetryInterval() {
                    return RETRY_INTERVAL;
                }
            });

    httpClientBuilder.setRetryHandler((exception, executionCount, context) -> {
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
        Uninterruptibles.sleepUninterruptibly(RETRY_INTERVAL, TimeUnit.MILLISECONDS);
        LOGGER.info("Encountered network error. Retrying request {},  Count {} Max is {}", currentReq.getURI(),
                executionCount, MAX_RETRIES);
        return executionCount <= MAX_RETRIES;
    });

    httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(TIMEOUT_MILLIS)
            .setConnectTimeout(TIMEOUT_MILLIS).setSocketTimeout(TIMEOUT_MILLIS).build());

    return httpClientBuilder.build();
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

static boolean isUseSSL3Only(final HttpContext context) {
    return "TRUE".equalsIgnoreCase((String) context.getAttribute(SSL3ONLY));
}