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.opensaml.util.http.HttpClientBuilder.java

/**
 * Constructs an {@link HttpClient} using the settings of this builder.
 * /*from www. j av  a  2 s  . c  o  m*/
 * @return the constructed client
 */
public HttpClient buildClient() {
    final DefaultHttpClient client = new DefaultHttpClient(buildConnectionManager());
    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    final HttpParams httpParams = client.getParams();

    if (socketLocalAddress != null) {
        httpParams.setParameter(AllClientPNames.LOCAL_ADDRESS, socketLocalAddress);
    }

    if (socketTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);
    }

    httpParams.setIntParameter(AllClientPNames.SOCKET_BUFFER_SIZE, socketBufferSize);

    if (connectionTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout);
    }

    httpParams.setBooleanParameter(AllClientPNames.STALE_CONNECTION_CHECK, connectionStalecheck);

    if (connectionProxyHost != null) {
        final HttpHost proxyHost = new HttpHost(connectionProxyHost, connectionProxyPort);
        httpParams.setParameter(AllClientPNames.DEFAULT_PROXY, proxyHost);

        if (connectionProxyUsername != null && connectionProxyPassword != null) {
            final CredentialsProvider credProvider = client.getCredentialsProvider();
            credProvider.setCredentials(new AuthScope(connectionProxyHost, connectionProxyPort),
                    new UsernamePasswordCredentials(connectionProxyUsername, connectionProxyPassword));
        }
    }

    httpParams.setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, httpFollowRedirects);

    httpParams.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, httpContentCharSet);

    return client;
}

From source file:com.pc.dailymile.DailyMileClient.java

private void initHttpClient() {
    HttpParams parameters = new BasicHttpParams();
    HttpProtocolParams.setVersion(parameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(parameters, HTTP.DEFAULT_CONTENT_CHARSET);
    // set the User-Agent to a common User-Agent because currently
    // the default httpclient User-Agent doesn't work with dailymile
    HttpProtocolParams.setUserAgent(parameters, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
    HttpProtocolParams.setUseExpectContinue(parameters, false);
    HttpConnectionParams.setTcpNoDelay(parameters, true);

    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager tsccm = new ThreadSafeClientConnManager(parameters, schReg);

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(tsccm, parameters);
    defaultHttpClient.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");
            }//from  w  w w . j av a  2 s  .c o m
        }
    });

    defaultHttpClient.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;
                    }
                }
            }
        }
    });
    httpClient = defaultHttpClient;
}

From source file:org.geomajas.layer.common.proxy.LayerHttpServiceImpl.java

/**
 * Check if there are interceptors & add to client if any.
 * //w w  w  .  j a va 2  s  .c  o  m
 * @param client
 * @param baseUrl
 */
private void addInterceptors(DefaultHttpClient client, String baseUrl, String layerId) {
    try {
        if (interceptors != null && baseUrl != null) {
            for (Entry<String, List<HttpRequestInterceptor>> entry : interceptors.getMap().entrySet()) {
                String key = entry.getKey();
                if ("".equals(key) || layerId.equals(key) || baseUrl.startsWith(key)) {
                    for (HttpRequestInterceptor inter : entry.getValue()) {
                        client.addRequestInterceptor(inter);
                    }
                }
            }
        }
    } catch (Exception e) {
        log.warn("Error adding interceptors: " + e.getMessage());
    }
}

From source file:org.apache.hive.service.cli.thrift.TestThriftHttpCLIService.java

/**
 * Test additional http headers passed to request interceptor.
 * @throws Exception/* w  w w  .j  av a 2 s.  co m*/
 */
@Test
public void testAdditionalHttpHeaders() throws Exception {
    TTransport transport;
    DefaultHttpClient hClient = new DefaultHttpClient();
    String httpUrl = transportMode + "://" + host + ":" + port + "/" + thriftHttpPath + "/";
    Map<String, String> additionalHeaders = new HashMap<String, String>();
    additionalHeaders.put("key1", "value1");
    additionalHeaders.put("key2", "value2");
    HttpBasicAuthInterceptorWithLogging authInt = new HttpBasicAuthInterceptorWithLogging(USERNAME, PASSWORD,
            null, null, false, additionalHeaders);
    hClient.addRequestInterceptor(authInt);
    transport = new THttpClient(httpUrl, hClient);
    TCLIService.Client httpClient = getClient(transport);

    // Create a new open session request object
    TOpenSessionReq openReq = new TOpenSessionReq();
    httpClient.OpenSession(openReq).getSessionHandle();
    ArrayList<String> headers = authInt.getRequestHeaders();

    for (String h : headers) {
        assertTrue(h.contains("key1:value1"));
        assertTrue(h.contains("key2:value2"));
    }
}

From source file:net.zypr.api.Protocol.java

private DefaultHttpClient getHTTPClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", _socketFactory, 443));
    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");
            }//from   w ww  .  ja  va  2  s .co m
        }
    });
    httpclient.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 index = 0; index < codecs.length; index++)
                    if (codecs[index].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
            }
        }
    });
    return (httpclient);
}

From source file:org.apache.hive.service.cli.thrift.TestThriftHttpCLIServiceFeatures.java

private void verifyForwardedHeaders(ArrayList<String> headerIPs, String cmd) throws Exception {
    TTransport transport;//from   w  w w .  j a  v  a  2s.  c  om
    DefaultHttpClient hClient = new DefaultHttpClient();
    String httpUrl = getHttpUrl();

    // add an interceptor that adds the X-Forwarded-For header with given ips
    if (!headerIPs.isEmpty()) {
        Header xForwardHeader = new BasicHeader("X-Forwarded-For", Joiner.on(",").join(headerIPs));
        RequestDefaultHeaders headerInterceptor = new RequestDefaultHeaders(Arrays.asList(xForwardHeader));
        hClient.addRequestInterceptor(headerInterceptor);
    }

    // interceptor for adding username, pwd
    HttpBasicAuthInterceptor authInt = new HttpBasicAuthInterceptor(ThriftCLIServiceTest.USERNAME,
            ThriftCLIServiceTest.PASSWORD, null, null, false, null);
    hClient.addRequestInterceptor(authInt);

    transport = new THttpClient(httpUrl, hClient);
    TCLIService.Client httpClient = getClient(transport);

    // Create a new open session request object
    TOpenSessionReq openReq = new TOpenSessionReq();
    TOpenSessionResp openResp = httpClient.OpenSession(openReq);

    //execute a query
    TExecuteStatementReq execReq = new TExecuteStatementReq(openResp.getSessionHandle(), "show tables");
    httpClient.ExecuteStatement(execReq);

    // capture arguments to authorizer impl call and verify ip addresses passed
    ArgumentCaptor<HiveAuthzContext> contextCapturer = ArgumentCaptor.forClass(HiveAuthzContext.class);

    verify(mockedAuthorizer).checkPrivileges(any(HiveOperationType.class),
            Matchers.anyListOf(HivePrivilegeObject.class), Matchers.anyListOf(HivePrivilegeObject.class),
            contextCapturer.capture());

    HiveAuthzContext context = contextCapturer.getValue();
    System.err.println("Forwarded IP Addresses " + context.getForwardedAddresses());

    List<String> auditIPAddresses = new ArrayList<String>(context.getForwardedAddresses());
    Collections.sort(auditIPAddresses);
    Collections.sort(headerIPs);

    Assert.assertEquals("Checking forwarded IP Address", headerIPs, auditIPAddresses);
}

From source file:org.apache.hive.service.cli.thrift.TestThriftHttpCLIServiceFeatures.java

/**
 * Test additional http headers passed to request interceptor.
 * @throws Exception/*from w  w  w  . j  a v a  2  s . co m*/
 */
@Test
public void testAdditionalHttpHeaders() throws Exception {
    TTransport transport;
    DefaultHttpClient hClient = new DefaultHttpClient();
    String httpUrl = getHttpUrl();
    Map<String, String> additionalHeaders = new HashMap<String, String>();
    additionalHeaders.put("key1", "value1");
    additionalHeaders.put("key2", "value2");
    HttpBasicAuthInterceptorWithLogging authInt = new HttpBasicAuthInterceptorWithLogging(
            ThriftCLIServiceTest.USERNAME, ThriftCLIServiceTest.PASSWORD, null, null, false, additionalHeaders);
    hClient.addRequestInterceptor(authInt);
    transport = new THttpClient(httpUrl, hClient);
    TCLIService.Client httpClient = getClient(transport);

    // Create a new open session request object
    TOpenSessionReq openReq = new TOpenSessionReq();
    httpClient.OpenSession(openReq).getSessionHandle();
    ArrayList<String> headers = authInt.getRequestHeaders();

    for (String h : headers) {
        assertTrue(h.contains("key1:value1"));
        assertTrue(h.contains("key2:value2"));
    }
}

From source file:com.su.search.client.solrj.PaHttpSolrServer.java

/**
 * Allow server->client communication to be compressed. Currently gzip and
 * deflate are supported. If the server supports compression the response will
 * be compressed./*from  www  . j a v  a 2s .c o m*/
 */
public void setAllowCompression(boolean allowCompression) {
    if (httpClient instanceof DefaultHttpClient) {
        final DefaultHttpClient client = (DefaultHttpClient) httpClient;
        client.removeRequestInterceptorByClass(UseCompressionRequestInterceptor.class);
        client.removeResponseInterceptorByClass(UseCompressionResponseInterceptor.class);
        if (allowCompression) {
            client.addRequestInterceptor(new UseCompressionRequestInterceptor());
            client.addResponseInterceptor(new UseCompressionResponseInterceptor());
        }
    } else {
        throw new UnsupportedOperationException("HttpClient instance was not of type DefaultHttpClient");
    }
}