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.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.//  ww w. j a va  2s . 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:com.vdisk.net.session.AbstractSession.java

/**
 * {@inheritDoc} <br/>/*from   ww w  .  j  av a2s  . c  o m*/
 * <br/>
 * The default implementation does all of this and more, including using a
 * connection pool and killing connections after a timeout to use less
 * battery power on mobile devices. It's unlikely that you'll want to change
 * this behavior.
 */
@Override
public synchronized HttpClient getHttpClient() {
    if (client == null) {
        // Set up default connection params. There are two routes to
        // VDisk - api server and content server.
        HttpParams connParams = new BasicHttpParams();
        ConnManagerParams.setMaxConnectionsPerRoute(connParams, new ConnPerRoute() {
            @Override
            public int getMaxForRoute(HttpRoute route) {
                return 10;
            }
        });
        ConnManagerParams.setMaxTotalConnections(connParams, 20);

        // Set up scheme registry.
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        try {
            schemeRegistry.register(new Scheme("https", TrustAllSSLSocketFactory.getDefault(), 443));
        } catch (Exception e) {
        }

        DBClientConnManager cm = new DBClientConnManager(connParams, schemeRegistry);

        // Set up client params.
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
        HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_TIMEOUT_MILLIS);
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
        HttpProtocolParams.setUserAgent(httpParams, makeUserAgent());
        httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, false);

        DefaultHttpClient c = new DefaultHttpClient(cm, httpParams) {
            @Override
            protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() {
                return new DBKeepAliveStrategy();
            }

            @Override
            protected ConnectionReuseStrategy createConnectionReuseStrategy() {
                return new DBConnectionReuseStrategy();
            }
        };

        c.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }
            }
        });

        c.addResponseInterceptor(new HttpResponseInterceptor() {
            @Override
            public void process(final HttpResponse response, final HttpContext context)
                    throws HttpException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    Header ceheader = entity.getContentEncoding();
                    if (ceheader != null) {
                        HeaderElement[] codecs = ceheader.getElements();
                        for (HeaderElement codec : codecs) {
                            if (codec.getName().equalsIgnoreCase("gzip")) {
                                response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                                return;
                            }
                        }
                    }
                }
            }
        });

        c.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

        client = c;
    }

    return client;
}

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

@PostConstruct
protected void initialize() {
    try {//from ww  w .ja  v a  2 s. c  o 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:org.overlord.sramp.client.SrampAtomApiClient.java

/**
 * Gets the content for an artifact as an input stream.  The caller must close the resulting
 * @param artifactType the artifact type
 * @param artifactUuid the S-RAMP uuid of the artifact
 * @return an {@link InputStream} to the S-RAMP artifact content
 * @throws SrampClientException
 * @throws SrampAtomException/*from w w  w .  j  a  v  a2 s . c  o  m*/
 */
public InputStream getArtifactContent(ArtifactType artifactType, String artifactUuid)
        throws SrampClientException, SrampAtomException {
    assertFeatureEnabled(artifactType);
    try {
        String atomUrl = String.format("%1$s/%2$s/%3$s/%4$s/media", this.endpoint, //$NON-NLS-1$
                artifactType.getArtifactType().getModel(), artifactType.getArtifactType().getType(),
                artifactUuid);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        if (this.authProvider != null) {
            httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                @Override
                public void process(HttpRequest request, HttpContext context)
                        throws HttpException, IOException {
                    authProvider.provideAuthentication(request);
                }
            });
        }
        HttpResponse response = httpClient.execute(new HttpGet(atomUrl));
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    } catch (Throwable e) {
        throw new SrampClientException(e);
    }
}

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   w ww . j  a v a  2 s  .  c om*/
    });
    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:edu.mit.mobile.android.locast.net.NetworkClient.java

/**
 * Makes a request to pair the device with the server. The server sends back a set of
 * credentials which are then stored for making further queries.
 *
 * @param pairCode//  w  ww .  ja va  2s. com
 *            the unique code that is provided by the server.
 * @return true if pairing process was successful, otherwise false.
 * @throws IOException
 * @throws JSONException
 * @throws RecordStoreException
 * @throws NetworkProtocolException
 */
public boolean pairDevice(String pairCode) throws IOException, JSONException, NetworkProtocolException {
    final DefaultHttpClient hc = new DefaultHttpClient();
    hc.addRequestInterceptor(REMOVE_EXPECTATIONS);
    final HttpPost r = new HttpPost(getFullUrlAsString(PATH_PAIR));

    final List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    parameters.add(new BasicNameValuePair("auth_secret", pairCode));
    r.setEntity(new UrlEncodedFormEntity(parameters));

    r.setHeader("Content-Type", URLEncodedUtils.CONTENT_TYPE);
    final HttpResponse c = hc.execute(r);

    checkStatusCode(c, false);

    // final JSONObject creds = toJsonObject(c);

    return true;
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse/*from  w w  w  .ja v a2  s .com*/
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}

From source file:com.antew.redditinpictures.library.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();//from ww  w  .ja  v a2 s.  c  o m
    Bundle extras = intent.getExtras();

    if (extras == null || action == null) {
        Ln.e("You did not pass extras or data with the Intent.");
        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    RequestCode requestCode = (RequestCode) extras.getSerializable(EXTRA_REQUEST_CODE);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    String cookie = extras.getString(EXTRA_COOKIE);
    String userAgent = extras.getString(EXTRA_USER_AGENT);

    // Items in this bundle are simply passed on in onRequestComplete
    Bundle passThrough = extras.getBundle(EXTRA_PASS_THROUGH);

    HttpEntity responseEntity = null;
    Intent result = new Intent(Constants.Broadcast.BROADCAST_HTTP_FINISHED);
    result.putExtra(EXTRA_PASS_THROUGH, passThrough);
    Bundle resultData = new Bundle();

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            DefaultHttpClient client = new DefaultHttpClient();

            // GZip requests
            // antew on 3/12/2014 - Disabling GZIP for now, need to figure this CloseGuard error:
            // 03-12 21:02:09.248    9674-9683/com.antew.redditinpictures.pro E/StrictMode A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
            //         java.lang.Throwable: Explicit termination method 'end' not called
            // at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            // at java.util.zip.Inflater.<init>(Inflater.java:82)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:96)
            // at java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:81)
            // at com.antew.redditinpictures.library.service.RESTService$GzipDecompressingEntity.getContent(RESTService.java:346)
            client.addRequestInterceptor(getGzipRequestInterceptor());
            client.addResponseInterceptor(getGzipResponseInterceptor());

            if (cookie != null) {
                request.addHeader("Cookie", cookie);
            }

            if (userAgent != null) {
                request.addHeader("User-Agent", Constants.Reddit.USER_AGENT);
            }

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Ln.d("Executing request: %s %s ", verbToString(verb), action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            if (responseEntity != null) {
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                resultData.putSerializable(EXTRA_REQUEST_CODE, requestCode);
                resultData.putInt(EXTRA_STATUS_CODE, statusCode);
                result.putExtra(EXTRA_BUNDLE, resultData);

                onRequestComplete(result);
            } else {
                onRequestFailed(result, statusCode);
            }
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect. %s %s ", verbToString(verb), action.toString());
        onRequestFailed(result, 0);
    } catch (UnsupportedEncodingException e) {
        Ln.e(e, "A UrlEncodedFormEntity was created with an unsupported encoding.");
        onRequestFailed(result, 0);
    } catch (ClientProtocolException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } catch (IOException e) {
        Ln.e(e, "There was a problem when sending the request.");
        onRequestFailed(result, 0);
    } finally {
        if (responseEntity != null) {
            try {
                responseEntity.consumeContent();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.artificer.client.ArtificerAtomApiClient.java

/**
 * Creates the client executor that will be used by RESTEasy when
 * making the request./*  w  ww. j  a  v a  2 s. c  o  m*/
 */
private ClientExecutor createClientExecutor() {
    // TODO I think the http client is thread safe - so let's try to create just one of these
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            Locale l = getLocale();
            if (l == null) {
                l = Locale.getDefault();
            }
            request.addHeader("Accept-Language", l.toString());
        }
    });
    if (this.authProvider != null) {
        httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                authProvider.provideAuthentication(request);
            }
        });
    }
    return new ApacheHttpClient4Executor(httpClient);
}

From source file:org.artificer.client.ArtificerAtomApiClient.java

/**
 * Gets the content for an artifact as an input stream.  The caller must close the resulting
 * @param artifactType the artifact type
 * @param artifactUuid the S-RAMP uuid of the artifact
 * @return an {@link InputStream} to the S-RAMP artifact content
 * @throws ArtificerClientException/*w w w .  j a  v  a2  s. c o m*/
 * @throws ArtificerServerException
 */
public InputStream getArtifactContent(ArtifactType artifactType, String artifactUuid)
        throws ArtificerClientException, ArtificerServerException {
    assertFeatureEnabled(artifactType);
    try {
        String atomUrl = String.format("%1$s/%2$s/%3$s/%4$s/media", srampEndpoint,
                artifactType.getArtifactType().getModel(), artifactType.getArtifactType().getType(),
                artifactUuid);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        if (this.authProvider != null) {
            httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                @Override
                public void process(HttpRequest request, HttpContext context)
                        throws HttpException, IOException {
                    authProvider.provideAuthentication(request);
                }
            });
        }
        HttpResponse response = httpClient.execute(new HttpGet(atomUrl));
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    } catch (Throwable e) {
        throw new ArtificerClientException(e);
    }
}