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

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

Introduction

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

Prototype

public synchronized void removeResponseInterceptorByClass(
            final Class<? extends HttpResponseInterceptor> clazz) 

Source Link

Usage

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.//from w w w.  j a  va  2s. c o 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 = 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  ww w .ja  va  2  s . com
 * @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.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java

public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.unregister("https");
    try {/*from   www. j av a  2  s . co m*/
        SSLContext instance = SSLContext.getInstance("TLS");
        TrustManager tm = UnsecureX509TrustManager.INSTANCE;
        instance.init(null, new TrustManager[] { tm }, null);
        schemeRegistry.register(new Scheme("https", 443,
                new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (Exception e) {
        throw new RuntimeException("TLS issue", e);
    }
    httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies());
    HttpParams params = httpclient.getParams();
    if (proxy != null) {
        ConnRouteParams.setDefaultProxy(params, proxy);
    }
    HttpConnectionParams.setSoTimeout(params, 7000);
    return httpclient;
}

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  w  w.  j a  va2  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:com.googlecode.sardine.FunctionalSardineTest.java

@Test
public void testGetRange() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException {
            // Verify partial content response
            assertEquals(206, r.getStatusLine().getStatusCode());
            assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE));
            assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length);
            client.removeResponseInterceptorByClass(this.getClass());
        }/*w w  w . ja  v a2 s .com*/
    });
    Sardine sardine = new SardineImpl(client);
    // mod_dav supports Range headers for GET
    final String url = "http://sudo.ch/dav/anon/sardine/single/file";
    // Resume
    final Map<String, String> header = Collections.singletonMap(HttpHeaders.RANGE, "bytes=" + 1 + "-");
    final InputStream in = sardine.get(url, header);
    assertNotNull(in);
}

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.jav  a 2 s  .c o  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:com.googlecode.sardine.FunctionalSardineTest.java

@Test
public void testGetSingleFileGzip() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException {
            assertEquals(200, r.getStatusLine().getStatusCode());
            assertNotNull(r.getHeaders(HttpHeaders.CONTENT_ENCODING));
            assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_ENCODING).length);
            assertEquals("gzip", r.getHeaders(HttpHeaders.CONTENT_ENCODING)[0].getValue());
            client.removeResponseInterceptorByClass(this.getClass());
        }/*from   w ww  . jav  a2 s  . co  m*/
    });
    Sardine sardine = new SardineImpl(client);
    sardine.enableCompression();
    //      final String url = "http://sardine.googlecode.com/svn/trunk/README.html";
    final String url = "http://sudo.ch/dav/anon/sardine/single/file";
    final InputStream in = sardine.get(url);
    assertNotNull(in);
    assertNotNull(in.read());
    try {
        in.close();
    } catch (EOFException e) {
        fail("Issue https://issues.apache.org/jira/browse/HTTPCLIENT-1075 pending");
    }
}

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. jav a2  s.co  m*/
 *
 * @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  2 s. c o  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();
}