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

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

Introduction

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

Prototype

public synchronized void removeRequestInterceptorByClass(final Class<? extends HttpRequestInterceptor> clazz) 

Source Link

Usage

From source file:org.pluroid.pluroium.HttpClientFactory.java

public static DefaultHttpClient createHttpClient(ClientConnectionManager connMgr) {
    DefaultHttpClient httpClient;
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.socket.timeout", new Integer(READ_TIMEOUT));
    params.setParameter("http.connection.timeout", new Integer(CONNECT_TIMEOUT));
    connMgr = new ThreadSafeClientConnManager(params, supportedSchemes);

    httpClient = new DefaultHttpClient(connMgr, params);
    httpClient.removeRequestInterceptorByClass(RequestExpectContinue.class);
    return httpClient;
}

From source file:de.escidoc.core.test.om.container.ContainerReferenceIT.java

/**
 * Retrieve the resource from the Framework via REST GET request.
 *
 * @param href The resource href.//ww w.  ja  v a 2s .  c om
 * @return The response object.
 * @throws Exception Thrown if the HTTP response value is != HTTP_OK (200)
 */
private HttpResponse call(final String href) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.removeRequestInterceptorByClass(RequestAddCookies.class);
    httpClient.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    String httpUrl = getFrameworkUrl() + href;

    HttpResponse httpRes = HttpHelper.doGet(httpClient, httpUrl, null);

    if (httpRes.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {

        throw new Exception("Retrieve of " + href + " failed. " + httpRes.getStatusLine().getReasonPhrase()
                + " - " + EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8));
    }

    return httpRes;
}

From source file:de.escidoc.core.test.om.container.ContainerReferenceTest.java

/**
 * Retrieve the resource from the Framework via REST GET request.
 *
 * @param href The resource href.//from   w ww . j  ava  2  s . co m
 * @return The response object.
 * @throws Exception Thrown if the HTTP response value is != HTTP_OK (200)
 */
private HttpResponse call(final String href) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.removeRequestInterceptorByClass(RequestAddCookies.class);
    httpClient.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    String httpUrl = Constants.PROTOCOL + "://" + Constants.HOST_PORT + href;

    HttpResponse httpRes = HttpHelper.doGet(httpClient, httpUrl, null);

    if (httpRes.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {

        throw new Exception("Retrieve of " + href + " failed. " + httpRes.getStatusLine().getReasonPhrase()
                + " - " + EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8));
    }

    return httpRes;
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

private void releaseClient(HttpClient client) {
    DefaultHttpClient dc = (DefaultHttpClient) client;
    dc.removeRequestInterceptorByClass(HostInterceptor.class);
    this.clients.checkin(dc);
}

From source file:com.googlecode.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuthHeader() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException {
            assertNotNull(r.getHeaders(HttpHeaders.AUTHORIZATION));
            assertEquals(1, r.getHeaders(HttpHeaders.AUTHORIZATION).length);
            client.removeRequestInterceptorByClass(this.getClass());
        }/*from w  w  w  .  j  a v  a2s .com*/
    });
    Sardine sardine = new SardineImpl(client);
    sardine.setCredentials("anonymous", null);
    // mod_dav supports Range headers for PUT
    final URI url = URI.create("http://sardine.googlecode.com/svn/trunk/README.html");
    sardine.enablePreemptiveAuthentication(url.getHost());
    assertTrue(sardine.exists(url.toString()));
}

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 w ww . j a  v a2 s. 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");
    }
}

From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java

@PostConstruct
protected void initialize() {
    try {//  w  w w .j ava 2s . co  m
        lock.writeLock().lock();

        httpParams = new BasicHttpParams();
        String userAgentString = "Apache Marmotta/"
                + configurationService.getStringConfiguration("kiwi.version") + " (running at "
                + configurationService.getServerUri() + ")" + " lmf-core/"
                + configurationService.getStringConfiguration("kiwi.version");
        userAgentString = configurationService.getStringConfiguration("core.http.user_agent", userAgentString);

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                configurationService.getIntConfiguration("core.http.so_timeout", 60000));
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                configurationService.getIntConfiguration("core.http.connection_timeout", 10000));

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

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

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS, 20));
        cm.setDefaultMaxPerRoute(
                configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS_PER_ROUTE, 10));

        final DefaultHttpClient hc = new DefaultHttpClient(cm, httpParams);
        hc.setRedirectStrategy(new LMFRedirectStrategy());
        hc.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        hc.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class);
        hc.addRequestInterceptor(new LMFRequestUserAgent(userAgentString));

        if (configurationService.getBooleanConfiguration(CoreOptions.HTTP_CLIENT_CACHE_ENABLE, true)) {
            CacheConfig cacheConfig = new CacheConfig();
            // FIXME: Hardcoded constants - is this useful?
            cacheConfig.setMaxCacheEntries(1000);
            cacheConfig.setMaxObjectSize(81920);

            final HttpCacheStorage cacheStore = new MapHttpCacheStorage(httpCache);

            this.httpClient = new MonitoredHttpClient(new CachingHttpClient(hc, cacheStore, cacheConfig));
        } else {
            this.httpClient = new MonitoredHttpClient(hc);
        }
        bytesSent.set(0);
        bytesReceived.set(0);
        requestsExecuted.set(0);

        idleConnectionMonitorThread = new IdleConnectionMonitorThread(httpClient.getConnectionManager());
        idleConnectionMonitorThread.start();

        StatisticsProvider stats = new StatisticsProvider(cm);
        statisticsService.registerModule(HttpClientService.class.getSimpleName(), stats);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:com.googlecode.sardine.FunctionalSardineTest.java

@Test
public void testPutRange() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    Sardine sardine = new SardineImpl(client);
    // mod_dav supports Range headers for PUT
    final String url = "http://sudo.ch/dav/anon/sardine/" + UUID.randomUUID().toString();
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException {
            assertEquals(201, r.getStatusLine().getStatusCode());
            client.removeResponseInterceptorByClass(this.getClass());
        }/*from  ww w . ja  v  a 2  s .  co  m*/
    });
    sardine.put(url, new ByteArrayInputStream("Te".getBytes("UTF-8")));

    try {
        // Append to existing file
        final Map<String, String> header = Collections.singletonMap(HttpHeaders.CONTENT_RANGE,
                "bytes " + 2 + "-" + 3 + "/" + 4);

        client.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest r, final HttpContext context)
                    throws HttpException, IOException {
                assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE));
                assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length);
                client.removeRequestInterceptorByClass(this.getClass());
            }
        });
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse r, final HttpContext context)
                    throws HttpException, IOException {
                assertEquals(204, r.getStatusLine().getStatusCode());
                client.removeResponseInterceptorByClass(this.getClass());
            }
        });
        sardine.put(url, new ByteArrayInputStream("st".getBytes("UTF-8")), header);

        assertEquals("Test", new BufferedReader(new InputStreamReader(sardine.get(url), "UTF-8")).readLine());
    } finally {
        sardine.delete(url);
    }
}

From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java

/**
 * Creates a new fetcher for fetching HTTP objects.  Not really suitable
 * for production use. Use of an HTTP proxy for security is also necessary
 * for production deployment./*from  w w  w  .  j a  va2  s.  c om*/
 *
 * @param maxObjSize          Maximum size, in bytes, of the object we will fetch, 0 if no limit..
 * @param connectionTimeoutMs timeout, in milliseconds, for connecting to hosts.
 * @param readTimeoutMs       timeout, in millseconds, for unresponsive connections
 * @param basicHttpFetcherProxy The http proxy to use.
 */
public BasicHttpFetcher(int maxObjSize, int connectionTimeoutMs, int readTimeoutMs,
        String basicHttpFetcherProxy) {
    // Create and initialize HTTP parameters
    setMaxObjectSizeBytes(maxObjSize);
    setSlowResponseWarning(DEFAULT_SLOW_RESPONSE_WARNING);

    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connectionTimeoutMs);

    // These are probably overkill for most sites.
    ConnManagerParams.setMaxTotalConnections(params, 1152);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(256));

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, "Apache Shindig");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    HttpConnectionParams.setConnectionTimeout(params, connectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, readTimeoutMs);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);

    HttpClientParams.setRedirecting(params, true);
    HttpClientParams.setAuthenticating(params, false);

    // Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    // Set proxy if set via guice.
    if (!StringUtils.isEmpty(basicHttpFetcherProxy)) {
        String[] splits = basicHttpFetcherProxy.split(":");
        ConnRouteParams.setDefaultProxy(client.getParams(),
                new HttpHost(splits[0], Integer.parseInt(splits[1]), "http"));
    }

    // try resending the request once
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));

    // Add hooks for gzip/deflate
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final org.apache.http.HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    });
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final org.apache.http.HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    for (HeaderElement codec : ceheader.getElements()) {
                        String codecname = codec.getName();
                        if ("gzip".equalsIgnoreCase(codecname)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        } else if ("deflate".equals(codecname)) {
                            response.setEntity(new DeflateDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler());

    // Disable automatic storage and sending of cookies (see SHINDIG-1382)
    client.removeRequestInterceptorByClass(RequestAddCookies.class);
    client.removeResponseInterceptorByClass(ResponseProcessCookies.class);

    // Use Java's built-in proxy logic in case no proxy set via guice.
    if (StringUtils.isEmpty(basicHttpFetcherProxy)) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    FETCHER = client;
}

From source file:de.escidoc.core.test.aa.AaTestBase.java

/**
 * Returns the status-code after calling the given url.
 * //from  w w  w.  j  a va  2s.  co m
 * @param url
 *            The url to call.
 * @return int status-code.
 * @throws Exception
 *             If anything fails.
 */
private int getStatusCode(final String url) throws Exception {
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.removeRequestInterceptorByClass(RequestAddCookies.class);
    httpClient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpClient.setRedirectHandler(new RedirectHandler() {
        @Override
        public URI getLocationURI(final HttpResponse response, final HttpContext context)
                throws ProtocolException {
            return null;
        }

        @Override
        public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
            return false;
        }
    });

    final HttpResponse httpRes = HttpHelper.doGet(httpClient, url, null);

    return httpRes.getStatusLine().getStatusCode();
}