Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

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

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Programmatic invocation.//from w  w  w .  j av a 2 s. c o  m
 * @param configServer   the configuration server for creating the REST server
 * @param restServer   the specification of the REST server
 */
public void makeServer(ConfigServer configServer, RESTServer restServer)
        throws ClientProtocolException, IOException, FactoryConfigurationError {

    DefaultHttpClient client = new DefaultHttpClient();

    String host = configServer.getHost();
    int configPort = configServer.getPort();

    // TODO: SSL
    Authentication authType = configServer.getAuthType();
    if (authType != null) {
        List<String> prefList = new ArrayList<String>();
        if (authType == Authentication.BASIC)
            prefList.add(AuthPolicy.BASIC);
        else if (authType == Authentication.DIGEST)
            prefList.add(AuthPolicy.DIGEST);
        else
            throw new IllegalArgumentException("Unknown authentication type: " + authType.name());
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);

        String configUser = configServer.getUser();
        String configPassword = configServer.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort),
                new UsernamePasswordCredentials(configUser, configPassword));
    }

    BasicHttpContext context = new BasicHttpContext();

    StringEntity content;
    try {
        content = new StringEntity(restServer.toXMLString());
    } catch (XMLStreamException e) {
        throw new IOException("Could not create payload to bootstrap server.");
    }
    content.setContentType("application/xml");

    HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis");
    poster.setEntity(content);

    HttpResponse response = client.execute(poster, context);
    //poster.releaseConnection();

    StatusLine status = response.getStatusLine();

    int statusCode = status.getStatusCode();
    String statusPhrase = status.getReasonPhrase();

    client.getConnectionManager().shutdown();

    if (statusCode >= 300) {
        throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n"
                + "Please check the server log for detail");
    }
}

From source file:com.radicaldynamic.groupinform.application.Collect.java

/**
 * Shared HttpContext so a user doesn't have to re-enter login information
 * @return//from   w w w  . j av  a 2s.  c om
 */
public synchronized HttpContext getHttpContext() {
    if (localContext == null) {
        // set up one context for all HTTP requests so that authentication
        // and cookies can be retained.
        localContext = new SyncBasicHttpContext(new BasicHttpContext());

        // establish a local cookie store for this attempt at downloading...
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // and establish a credentials provider.  Default is 7 minutes.
        CredentialsProvider credsProvider = new AgingCredentialsProvider(7 * 60 * 1000);
        localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    }
    return localContext;
}

From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java

protected HttpContext createContext() {
    return new BasicHttpContext();
}

From source file:com.uwindsor.elgg.project.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  ww  w.j  a  v a2  s  .  c  o  m
 */
public AsyncHttpClient() {

    BasicHttpParams httpParams = new BasicHttpParams();

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

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    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()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(HttpResponse response, HttpContext context) {

            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

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  ww.ja v  a  2s  .  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:com.marklogic.client.tutorial.util.Bootstrapper.java

/**
 * Programmatic invocation.//from   w  w  w .j a  va2  s  . c  om
 * @param configServer   the configuration server for creating the REST server
 * @param restServer   the specification of the REST server
 */
public void makeServer(ConfigServer configServer, RESTServer restServer)
        throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError {

    DefaultHttpClient client = new DefaultHttpClient();

    String host = configServer.getHost();
    int configPort = configServer.getPort();

    Authentication authType = configServer.getAuthType();
    if (authType != null) {
        List<String> prefList = new ArrayList<String>();
        if (authType == Authentication.BASIC)
            prefList.add(AuthPolicy.BASIC);
        else if (authType == Authentication.DIGEST)
            prefList.add(AuthPolicy.DIGEST);
        else
            throw new IllegalArgumentException("Unknown authentication type: " + authType.name());
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);

        String configUser = configServer.getUser();
        String configPassword = configServer.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort),
                new UsernamePasswordCredentials(configUser, configPassword));
    }

    BasicHttpContext context = new BasicHttpContext();

    StringEntity content = new StringEntity(restServer.toXMLString());
    content.setContentType("application/xml");

    HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis");
    poster.setEntity(content);

    HttpResponse response = client.execute(poster, context);
    //poster.releaseConnection();

    StatusLine status = response.getStatusLine();

    int statusCode = status.getStatusCode();
    String statusPhrase = status.getReasonPhrase();

    client.getConnectionManager().shutdown();

    if (statusCode >= 300) {
        throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n"
                + "Please check the server log for detail");
    }
}

From source file:com.vc.net.AsyncHttpClient.java

public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

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

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

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("uroad-android-httpclient/%s (http://www.u-road.com/)", VERSION));
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//from ww  w .j a va  2 s. c  om
        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()) {
                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(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
            DEFAULT_KEEP_ALIVETIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.androidrocks.bex.zxing.client.android.AndroidHttpClient.java

private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
    this.delegate = new DefaultHttpClient(ccm, params) {
        @Override//from w  w  w . ja v a2  s .  co m
        protected BasicHttpProcessor createHttpProcessor() {
            // Add interceptor to prevent making requests from main thread.
            BasicHttpProcessor processor = super.createHttpProcessor();
            processor.addRequestInterceptor(sThreadCheckInterceptor);
            return processor;
        }

        @Override
        protected HttpContext createHttpContext() {
            // Same as DefaultHttpClient.createHttpContext() minus the
            // cookie store.
            HttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
            context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
            context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
            return context;
        }
    };
}

From source file:com.mpower.mintel.android.application.MIntel.java

/**
 * Shared HttpContext so a user doesn't have to re-enter login information
 * /* w  w w.  j av a2s. c  o  m*/
 * @return
 */
public synchronized HttpContext getHttpContext() {
    if (localContext == null) {
        // set up one context for all HTTP requests so that authentication
        // and cookies can be retained.
        localContext = new SyncBasicHttpContext(new BasicHttpContext());

        // establish a local cookie store for this attempt at downloading...
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // and establish a credentials provider. Default is 7 minutes.
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    }
    return localContext;
}

From source file:com.frand.easyandroid.http.FFHttpClient.java

public FFHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

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

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

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override/*  w w  w  .  ja va 2  s.  c o m*/
        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()) {
                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(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new FFRetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
            DEFAULT_KEEP_ALIVETIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
            new ThreadPoolExecutor.CallerRunsPolicy());

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}