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:Main.java

public static void PostRequest(String url, Map<String, String> params, String userName, String password,
        Handler messageHandler) {
    HttpPost postMethod = new HttpPost(url);
    List<NameValuePair> nvps = null;
    DefaultHttpClient client = new DefaultHttpClient();

    if ((userName != null) && (userName.length() > 0) && (password != null) && (password.length() > 0)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));
    }/*from w ww  . jav  a  2 s  .  c om*/

    final Map<String, String> sendHeaders = new HashMap<String, String>();
    sendHeaders.put(CONTENT_TYPE, MIME_FORM_ENCODED);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            for (String key : sendHeaders.keySet()) {
                if (!request.containsHeader(key)) {
                    request.addHeader(key, sendHeaders.get(key));
                }
            }
        }
    });

    if ((params != null) && (params.size() > 0)) {
        nvps = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
    }
    if (nvps != null) {
        try {
            postMethod.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    ExecutePostRequest(client, postMethod, GetResponseHandlerInstance(messageHandler));
}

From source file:eu.masconsult.bgbanking.banks.fibank.my.MyFIBankClient.java

/**
 * Configures the httpClient to connect to the URL provided.
 *///from w ww  .j av a2s  .c  o m
private static DefaultHttpClient getHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    // HttpClientParams.setRedirecting(params, false);
    httpClient.addRequestInterceptor(new DumpHeadersRequestInterceptor());
    httpClient.addResponseInterceptor(new DumpHeadersResponseInterceptor());
    return httpClient;
}

From source file:com.rsegismont.androlife.core.utils.AndrolifeUtils.java

private static InputStream getInputStreamFromUrl(Context paramContext, String paramString) {
    if (confirmDownload(paramContext, paramString)) {
        try {/* ww  w  .  j a  va  2  s .  c o  m*/
            BasicHttpParams localBasicHttpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 30000);
            HttpConnectionParams.setSoTimeout(localBasicHttpParams, 30000);
            DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(localBasicHttpParams);
            localDefaultHttpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                public void process(HttpRequest paramAnonymousHttpRequest,
                        HttpContext paramAnonymousHttpContext) {
                    if (!paramAnonymousHttpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
                        paramAnonymousHttpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
                    }
                }
            });
            localDefaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                public void process(HttpResponse paramAnonymousHttpResponse,
                        HttpContext paramAnonymousHttpContext) {
                    Header localHeader = paramAnonymousHttpResponse.getEntity().getContentEncoding();
                    HeaderElement[] arrayOfHeaderElement = null;
                    int i;
                    if (localHeader != null) {
                        arrayOfHeaderElement = localHeader.getElements();
                        i = arrayOfHeaderElement.length;
                        for (int j = 0; j < i; j++) {

                            if (arrayOfHeaderElement[j].getName().equalsIgnoreCase(ENCODING_GZIP)) {
                                paramAnonymousHttpResponse.setEntity(new AndrolifeUtils.InflatingEntity(
                                        paramAnonymousHttpResponse.getEntity()));
                                return;
                            }
                        }
                    }

                }
            });
            InputStream localInputStream = localDefaultHttpClient.execute(new HttpGet(paramString)).getEntity()
                    .getContent();
            return localInputStream;
        } catch (Exception localException) {
        }
        return null;
    } else {
        return null;
    }
}

From source file:com.bt.download.android.core.HttpFetcher.java

private static HttpClient setupHttpClient(boolean gzip) {
    SSLSocketFactory.getSocketFactory().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(20));
    params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 200);
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, new BasicHttpParams());
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_RETRY_COUNT, true));

    if (gzip) {//from  w  w  w .  j  a  v  a 2  s .c  o  m
        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }
        });

        httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(HttpResponse response, 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;
                        }
                    }
                }
            }
        });
    }

    return httpClient;
}

From source file:sand.actionhandler.weibo.UdaClient.java

private static DefaultHttpClient createHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    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. j  ava 2 s  .  c om*/
        }

    });

    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 i = 0; i < codecs.length; i++) {
                    if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });
    return httpclient;
}

From source file:eu.masconsult.bgbanking.banks.sgexpress.SGExpressClient.java

/**
 * Configures the httpClient to connect to the URL provided.
 * /*  w  w w.ja va 2 s .c o m*/
 * @param authToken
 */
private static DefaultHttpClient getHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    final HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpClientParams.setRedirecting(params, false);
    HttpClientParams.setCookiePolicy(params, CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.addRequestInterceptor(new DumpHeadersRequestInterceptor());
    httpClient.addResponseInterceptor(new DumpHeadersResponseInterceptor());
    httpClient.addResponseInterceptor(new CookieQuotesFixerResponseInterceptor());
    return httpClient;
}

From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java

private static HttpClient getNewHttpClient() throws WSException {

    try {/*from  w  w  w. j  a  va 2s  .com*/
        TrustStrategy trustStrategy = new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        };
        SSLSocketFactory sf = new CustomSSLFactory(trustStrategy);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(sr);

        DefaultHttpClient client = new DefaultHttpClient(ccm);
        client.setHttpRequestRetryHandler(new CustomHttpRequestRetryHandler());
        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        List<String> authpref = new ArrayList<String>();
        // Choose BASIC over DIGEST for proxy authentication
        authpref.add(AuthPolicy.BASIC);
        authpref.add(AuthPolicy.DIGEST);
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);

        client.addRequestInterceptor(new CustomHttpRequestInterceptor());
        client.addResponseInterceptor(new CustomHttpResponseInterceptor());

        return client;

    } catch (Exception e) {
        throw new WSException("Error while creating a HTTP client.", e);
    }
}

From source file:org.n52.oxf.util.web.GzipEnabledHttpClient.java

private void addGzipInterceptors(DefaultHttpClient httpclient) {
    httpclient.addRequestInterceptor(new GzipRequestInterceptor());
    httpclient.addResponseInterceptor(new GzipResponseInterceptor());
}

From source file:org.openremote.container.web.ProxyWebClientBuilder.java

@SuppressWarnings("deprecation")
@Override//w w  w .jav  a 2  s .c  om
protected ClientHttpEngine initDefaultEngine() {
    ApacheHttpClient4Engine engine = (ApacheHttpClient4Engine) super.initDefaultEngine();
    DefaultHttpClient httpClient = (DefaultHttpClient) engine.getHttpClient();
    httpClient.addRequestInterceptor((request, context) -> request.setHeader(HTTP.TARGET_HOST,
            new HttpHost(proxyHost, proxyPort).toHostString()));
    return engine;
}

From source file:org.n52.oxf.util.web.AuthTokenAwareHttpClient.java

private void decorateAuthtokenAwareness(String authtoken) {
    DefaultHttpClient clientToDecorate = getHttpClientToDecorate();
    clientToDecorate.addRequestInterceptor(new AuthTokenInterceptor(authtoken));
}