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, final int index) 

Source Link

Usage

From source file:org.springframework.ws.transport.http.HttpComponentsMessageSender.java

/**
 * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient} that uses a
 * default {@link SingleClientConnManager}.
 *///from  www. j ava 2s  .com
public HttpComponentsMessageSender() {
    DefaultHttpClient defaultClient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    defaultClient.addRequestInterceptor(new RemoveSoapHeadersInterceptor(), 0);

    this.httpClient = defaultClient;
    setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT_MILLISECONDS);
    setReadTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS);
}

From source file:org.jets3t.service.utils.RestUtils.java

public static HttpClient initHttpsConnection(final JetS3tRequestAuthorizer requestAuthorizer,
        Jets3tProperties jets3tProperties, String userAgentDescription,
        CredentialsProvider credentialsProvider) {
    // Configure HttpClient properties based on Jets3t Properties.
    HttpParams params = createDefaultHttpParams();
    params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties);

    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty(
            ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName()));

    HttpConnectionParams.setConnectionTimeout(params,
            jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000));
    HttpConnectionParams.setSoTimeout(params,
            jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000));
    HttpConnectionParams.setStaleCheckingEnabled(params,
            jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true));

    // Connection properties to take advantage of S3 window scaling.
    if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) {
        HttpConnectionParams.setSocketBufferSize(params,
                jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0));
    }//from ww w.j a  va 2  s  . co  m

    HttpConnectionParams.setTcpNoDelay(params, true);

    // Set user agent string.
    String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null);
    if (userAgent == null) {
        userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription);
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting user agent string: " + userAgent);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true);
    HttpProtocolParams.setUseExpectContinue(params, expectContinue);

    long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout",
            0);
    ConnManagerParams.setTimeout(params, connectionManagerTimeout);

    DefaultHttpClient httpClient = wrapClient(params);
    httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler(
            jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer));

    if (credentialsProvider != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName());
        }
        httpClient.setCredentialsProvider(credentialsProvider);
        if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) {
            // Add as the very first interceptor in the protocol chain
            httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0);
        }
    }
    return httpClient;
}

From source file:org.jets3t.service.utils.RestUtils.java

/**
 * Initialises, or re-initialises, the underlying HttpConnectionManager and
 * HttpClient objects a service will use to communicate with an AWS service.
 * If proxy settings are specified in this service's {@link Jets3tProperties} object,
 * these settings will also be passed on to the underlying objects.
 *//* w w  w  . ja  v a 2s .  c o  m*/
public static HttpClient initHttpConnection(final JetS3tRequestAuthorizer requestAuthorizer,
        Jets3tProperties jets3tProperties, String userAgentDescription,
        CredentialsProvider credentialsProvider) {
    // Configure HttpClient properties based on Jets3t Properties.
    HttpParams params = createDefaultHttpParams();
    params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties);

    params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty(
            ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName()));

    HttpConnectionParams.setConnectionTimeout(params,
            jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000));
    HttpConnectionParams.setSoTimeout(params,
            jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000));
    HttpConnectionParams.setStaleCheckingEnabled(params,
            jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true));

    // Connection properties to take advantage of S3 window scaling.
    if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) {
        HttpConnectionParams.setSocketBufferSize(params,
                jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0));
    }

    HttpConnectionParams.setTcpNoDelay(params, true);

    // Set user agent string.
    String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null);
    if (userAgent == null) {
        userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription);
    }
    if (log.isDebugEnabled()) {
        log.debug("Setting user agent string: " + userAgent);
    }
    HttpProtocolParams.setUserAgent(params, userAgent);

    boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true);
    HttpProtocolParams.setUseExpectContinue(params, expectContinue);

    long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout",
            0);
    ConnManagerParams.setTimeout(params, connectionManagerTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler(
            jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer));

    if (credentialsProvider != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName());
        }
        httpClient.setCredentialsProvider(credentialsProvider);
        if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) {
            // Add as the very first interceptor in the protocol chain
            httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0);
        }
    }

    return httpClient;
}

From source file:com.ibm.sbt.services.endpoints.SSOEndpoint.java

@Override
public void initialize(DefaultHttpClient httpClient) {
    HttpRequestInterceptor ltpaInterceptor = new LtpaInterceptor(getUrl(), getDomain());
    httpClient.addRequestInterceptor(ltpaInterceptor, 0);
}

From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java

protected String getData(URI location) throws APIException {
    Log.d("HTTPAPIRequest", "Downloading " + location);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(location);
    client.addRequestInterceptor(preemptiveAuth, 0);

    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    if (!m_params.isEmpty()) {
        MultipartEntity params = new MultipartEntity();
        for (Entry<String, Object> item : m_params.entrySet()) {
            Object value = item.getValue();
            ContentBody data;// ww  w .jav  a  2  s  . c  o  m
            if (value instanceof Attachment) {
                Attachment attachment = (Attachment) value;
                try {
                    data = new InputStreamBody(attachment.getStream(), attachment.contentType(),
                            attachment.name());
                    Log.d("HTTPAPIRequest",
                            "Found a " + attachment.contentType() + " attachment named " + attachment.name());
                } catch (FileNotFoundException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                } catch (IOException e) {
                    getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND);
                    throw new APIException();
                }
            } else {
                try {
                    data = new StringBody(value.toString());
                } catch (UnsupportedEncodingException e) {
                    getRequest().setError(ErrorType.ERROR_INTERNAL);
                    throw new APIException();
                }
            }
            params.addPart(item.getKey(), data);
        }
        post.setEntity(params);
    }

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(),
            m_api.getAccount().getPassword());
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

    HttpResponse req;
    try {
        req = client.execute(post);
    } catch (ClientProtocolException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    } catch (IOException e3) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED);
        throw new APIException();
    }

    InputStream result;
    try {
        result = req.getEntity().getContent();
    } catch (IllegalStateException e1) {
        getRequest().setError(ErrorType.ERROR_INTERNAL);
        throw new APIException();
    } catch (IOException e1) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }

    InputStreamReader in = null;
    int status;
    in = new InputStreamReader(result);
    status = req.getStatusLine().getStatusCode();
    Log.d("HTTPAPIRequest", "Got status code of " + status);
    setStatusCode(status);
    if (status >= 300 || status < 200) {
        getRequest().setError(ErrorType.ERROR_SERVER);
        Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status);
        throw new APIException();
    }

    int totalSize = -1;
    if (req.containsHeader("Content-length"))
        totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue());

    char[] buffer = new char[1024];
    //2^17 = 131072.
    StringBuilder contents = new StringBuilder(131072);
    try {
        int size = 0;
        while ((totalSize > 0 && size < totalSize) || totalSize == -1) {
            int readSize = in.read(buffer);
            size += readSize;
            if (readSize == -1)
                break;
            if (totalSize >= 0)
                getRequest().publishProgress(new APIProgress((size / totalSize) * 5000));
            contents.append(buffer, 0, readSize);
        }
    } catch (IOException e) {
        getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN);
        throw new APIException();
    }
    return contents.toString();
}

From source file:org.energyos.espi.thirdparty.web.ClientRestTemplate.java

public ClientRestTemplate(String username, String password) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    httpClient.setCredentialsProvider(credentialsProvider);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    this.setRequestFactory(rf);
}

From source file:de.escidoc.core.test.common.fedora.TripleStoreTestBase.java

/**
 * Request SPO query to MPT triple store.
 *
 * @param spoQuery     The SPO query./*from   w w w.  ja v a 2 s.co  m*/
 * @param outputFormat The triple store output format (N-Triples/RDF/XML/Turtle/..)
 * @return query result
 * @throws Exception If anything fails.
 */
public String requestMPT(final String spoQuery, final String outputFormat) throws Exception {
    HttpPost post = new HttpPost(getFedoraUrl() + "/risearch");
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("format", outputFormat));
    formparams.add(new BasicNameValuePair("query", spoQuery));
    formparams.add(new BasicNameValuePair("type", TYPE_MPT));
    formparams.add(new BasicNameValuePair("lang", LANG_MPT));
    // The flush parameter tells the resource index to ensure
    // that any recently-added/modified/deleted triples are
    // flushed to the triplestore before executing the query.
    formparams.add(new BasicNameValuePair("flush", FLUSH));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
    post.setEntity(entity);

    int resultCode = 0;
    try {
        DefaultHttpClient httpClient = getHttpClient();
        BasicHttpContext localcontext = new BasicHttpContext();
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
        HttpResponse httpRes = httpClient.execute(post, localcontext);
        if (httpRes.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            throw new Exception("Bad request. Http response : " + resultCode);
        }

        String result = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
        if (result == null) {
            return null;
        }
        if (result.startsWith("<html")) {
            Pattern p = Pattern.compile(QUERY_ERROR);
            Matcher m = p.matcher(result);

            Pattern p1 = Pattern.compile(PARSE_ERROR);
            Matcher m1 = p1.matcher(result);

            Pattern p2 = Pattern.compile(FORMAT_ERROR);
            Matcher m2 = p2.matcher(result);
            if (m.find()) {
                result = Constants.CDATA_START + result + Constants.CDATA_END;
                if (m1.find()) {
                    throw new Exception(result);
                } else if (m2.find()) {
                    throw new Exception(result);
                }
            } else {
                result = Constants.CDATA_START + result + Constants.CDATA_END;
                throw new Exception("Request to MPT failed." + result);
            }
        }

        return result;
    } catch (final Exception e) {
        throw new Exception(e.toString(), e);
    }
}

From source file:org.gradle.internal.resource.transport.http.HttpClientConfigurer.java

private void configureCredentials(DefaultHttpClient httpClient, PasswordCredentials credentials) {
    String username = credentials.getUsername();
    if (username != null && username.length() > 0) {
        useCredentials(httpClient, credentials, AuthScope.ANY_HOST, AuthScope.ANY_PORT);

        // Use preemptive authorisation if no other authorisation has been established
        httpClient.addRequestInterceptor(new PreemptiveAuth(new BasicScheme()), 0);
    }// ww  w. ja v a 2  s  .  co m
}

From source file:com.ibm.sbt.services.endpoints.FormEndpoint.java

@Override
public void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
    if (StringUtil.isNotEmpty(getCookieCache())) {
        HttpRequestInterceptor basicInterceptor = new CookieInterceptor(getCookieCache());
        httpClient.addRequestInterceptor(basicInterceptor, 0);
    }// www. jav  a 2s. c om
}

From source file:com.ibm.sbt.services.endpoints.OAuthEndpoint.java

@Override
public void initialize(DefaultHttpClient httpClient) throws ClientServicesException {
    try {// w  ww.  j a  v  a  2 s .  c om
        AccessToken token = oAuthHandler.acquireToken(false);
        if ((token != null) && (oAuthHandler != null)) {
            HttpRequestInterceptor oauthInterceptor = new OAuthInterceptor(token, super.getUrl(), oAuthHandler);
            httpClient.addRequestInterceptor(oauthInterceptor, 0);
        }
    } catch (OAuthException ex) {
        throw new ClientServicesException(ex);
    }
}