Example usage for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor

List of usage examples for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient addRequestInterceptor.

Prototype

public synchronized void addRequestInterceptor(final HttpRequestInterceptor itcp) 

Source Link

Usage

From source file:org.apache.hive.jdbc.miniHS2.TestHs2ConnectionMetricsHttp.java

private TCLIService.Client getHttpClient() throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    Map<String, String> headers = new HashMap<>();
    headers.put("Connection", "close");
    httpClient.addRequestInterceptor(
            new BasicHttpRequestInterceptor(USERNAME, PASSWORD, null, null, false, headers));

    TTransport transport = new THttpClient(getHttpUrl(), httpClient);
    TProtocol protocol = new TBinaryProtocol(transport);
    return new TCLIService.Client(protocol);
}

From source file:com.todoroo.andlib.service.HttpRestClient.java

@SuppressWarnings("nls")
protected void actsAsGzippable(DefaultHttpClient client) {
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding"))
                request.addHeader("Accept-Encoding", "gzip");
        }/*w ww  .  ja  v a  2  s  .co m*/

    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

private void registerInterceptors(DefaultHttpClient httpclient) {
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (log.isInfoEnabled()) {
                RequestLine req = request.getRequestLine();
                log.info("> " + req.getMethod() + URLDecoder.decode(req.getUri(), "UTF-8"));
            }/*from  w  w w  .  j a  v a 2 s  .c o  m*/
        }
    });
    httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            if (log.isInfoEnabled()) {
                log.info("< Status: " + response.getStatusLine().getStatusCode());
            }
            validate(response);
        }
    });
}

From source file:org.jasig.portal.security.provider.saml.SAMLSession.java

/**
 * Public constructor that initializes the SAML session.  This sets up the
 * ThreadSafeConnectionManager because the connection interceptor will be
 * making a secondary connection to authenticate to the IdP while the
 * primary connection is blocked. //from   w w  w. j av a  2  s .  c  o  m
 * 
 * @param samlAssertion SAML assertion that was passed to the portal for authentication
 * @param connectionManager The connection manager to use for the {@link HttpClient} used for making authenticated requests. The caller is responsible for the {@link ClientConnectionManager} lifecycle.
 * @param params the {@link HttpClient} configuration parameters to use.
 */
public SAMLSession(String samlAssertion, ClientConnectionManager connectionManager, HttpParams params) {
    final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params);
    client.addRequestInterceptor(new HttpRequestPreprocessor());
    client.addResponseInterceptor(new HttpRequestPostprocessor(this));
    this.wspHttpClient = client;
    this.samlAssertion = samlAssertion;
}

From source file:org.valkyriercp.security.remoting.BasicAuthCommonsHttpInvokerProxyFactoryBean.java

/**
 * Handle a change in the current authentication token.
 * This method will fail fast if the executor isn't a CommonsHttpInvokerRequestExecutor.
 * @see org.valkyriercp.security.AuthenticationAware#setAuthenticationToken(org.springframework.security.core.Authentication)
 */// w  w  w .  j ava2s  . c  o  m
public void setAuthenticationToken(Authentication authentication) {
    if (logger.isDebugEnabled()) {
        logger.debug("New authentication token: " + authentication);
    }

    HttpComponentsHttpInvokerRequestExecutor executor = (HttpComponentsHttpInvokerRequestExecutor) getHttpInvokerRequestExecutor();
    DefaultHttpClient httpClient = (DefaultHttpClient) executor.getHttpClient();
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    httpClient.setCredentialsProvider(provider);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor());
    UsernamePasswordCredentials usernamePasswordCredentials;
    if (authentication != null) {
        usernamePasswordCredentials = new UsernamePasswordCredentials(authentication.getName(),
                authentication.getCredentials().toString());
    } else {
        usernamePasswordCredentials = null;
    }
    provider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
}

From source file:com.google.pubsub.clients.common.MetricsHandler.java

private void initialize() {
    synchronized (this) {
        try {//from  ww w.  j a v  a 2 s  .c om
            HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            GoogleCredential credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(
                        Collections.singletonList("https://www.googleapis.com/auth/cloud-platform"));
            }
            monitoring = new Monitoring.Builder(transport, jsonFactory, credential)
                    .setApplicationName("Cloud Pub/Sub Loadtest Framework").build();
            String zoneId;
            String instanceId;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.addRequestInterceptor(new RequestAcceptEncoding());
                httpClient.addResponseInterceptor(new ResponseContentEncoding());

                HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
                HttpConnectionParams.setSoKeepalive(httpClient.getParams(), true);
                HttpConnectionParams.setStaleCheckingEnabled(httpClient.getParams(), false);
                HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);

                SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
                schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
                httpClient.setKeepAliveStrategy((response, ctx) -> 30);
                HttpGet zoneIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/zone");
                zoneIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse zoneIdResponse = httpClient.execute(zoneIdRequest);
                String tempZoneId = EntityUtils.toString(zoneIdResponse.getEntity());
                if (tempZoneId.lastIndexOf("/") >= 0) {
                    zoneId = tempZoneId.substring(tempZoneId.lastIndexOf("/") + 1);
                } else {
                    zoneId = tempZoneId;
                }
                HttpGet instanceIdRequest = new HttpGet(
                        "http://metadata.google.internal/computeMetadata/v1/instance/id");
                instanceIdRequest.setHeader("Metadata-Flavor", "Google");
                HttpResponse instanceIdResponse = httpClient.execute(instanceIdRequest);
                instanceId = EntityUtils.toString(instanceIdResponse.getEntity());
            } catch (IOException e) {
                log.info("Unable to connect to metadata server, assuming not on GCE, setting "
                        + "defaults for instance and zone.");
                instanceId = "local";
                zoneId = "us-east1-b"; // Must use a valid cloud zone even if running local.
            }

            monitoredResource.setLabels(
                    ImmutableMap.of("project_id", project, "instance_id", instanceId, "zone", zoneId));
            createMetrics();
        } catch (IOException e) {
            log.error("Unable to initialize MetricsHandler, trying again.", e);
            executor.execute(this::initialize);
        } catch (GeneralSecurityException e) {
            log.error("Unable to initialize MetricsHandler permanently, credentials error.", e);
        }
    }
}

From source file:org.dasein.security.joyent.DefaultClientFactory.java

@Override
public @Nonnull HttpClient getClient(String endpoint) throws CloudException, InternalException {
    if (providerContext == null) {
        throw new CloudException("No context was defined for this request");
    }/*from   w ww  .ja va  2  s . c  o m*/

    final HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString());
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = providerContext.getCustomProperties();
    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPortStr = p.getProperty("proxyPort");
        int proxyPort = 0;
        if (proxyPortStr != null) {
            proxyPort = Integer.parseInt(proxyPortStr);
        }
        if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);
    // Joyent does not support gzip at the moment (7.2), but in case it will
    // in the future we might just leave these here
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
            request.setParams(params);
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header header = entity.getContentEncoding();
                if (header != null) {
                    for (HeaderElement codec : header.getElements()) {
                        if (codec.getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }
        }
    });
    return client;
}

From source file:org.artificer.test.maven.ArtificerMavenTest.java

private ClientExecutor createClientExecutor() {
    final BasicAuthenticationProvider authProvider = new BasicAuthenticationProvider("admin", "artificer1!");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//from w  ww  . ja  v a 2  s.c o  m
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            authProvider.provideAuthentication(request);
        }
    });
    return new ApacheHttpClient4Executor(httpClient);
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static HttpClient newHttpClient() {
    int timeout = 3 * 60 * 1000;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    ClientConnectionManager mgr = httpClient.getConnectionManager();
    HttpParams params = httpClient.getParams();
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry());
    httpClient = new DefaultHttpClient(cm, params);

    // how long are we prepared to wait to establish a connection?
    HttpConnectionParams.setConnectionTimeout(params, timeout);

    // how long should the socket wait for data?
    HttpConnectionParams.setSoTimeout(params, timeout);

    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false) {

        @Override//from   w w w.  j  a  va  2s  .c  o  m
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return super.retryRequest(exception, executionCount, context);
        }

        @Override
        public boolean isRequestSentRetryEnabled() {
            return false;
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            response.removeHeaders("Set-Cookie");

            HttpEntity entity = response.getEntity();
            Header contentEncodingHeader = entity.getContentEncoding();
            if (contentEncodingHeader != null) {
                HeaderElement[] codecs = contentEncodingHeader.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }

        }

    });
    return httpClient;
}

From source file:org.dasein.cloud.digitalocean.DigitalOcean.java

public @Nonnull HttpClient getClient(boolean multipart) throws InternalException {
    ProviderContext ctx = getContext();/*from w  w  w  . j a  v a 2s  . co m*/
    if (ctx == null) {
        throw new InternalException("No context was specified for this request");
    }

    final HttpParams params = new BasicHttpParams();
    int timeout = 15000;
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
        HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString());
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();
    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPortStr = p.getProperty("proxyPort");
        int proxyPort = 0;
        if (proxyPortStr != null) {
            proxyPort = Integer.parseInt(proxyPortStr);
        }
        if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
            request.setParams(params);
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header header = entity.getContentEncoding();
                if (header != null) {
                    for (HeaderElement codec : header.getElements()) {
                        if (codec.getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }
        }
    });
    return client;
}