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

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

Introduction

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

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:org.opensaml.util.http.HttpClientBuilder.java

/**
 * Constructs an {@link HttpClient} using the settings of this builder.
 * /* w  w w .  j  a  va2  s . com*/
 * @return the constructed client
 */
public HttpClient buildClient() {
    final DefaultHttpClient client = new DefaultHttpClient(buildConnectionManager());
    client.addRequestInterceptor(new RequestAcceptEncoding());
    client.addResponseInterceptor(new ResponseContentEncoding());

    final HttpParams httpParams = client.getParams();

    if (socketLocalAddress != null) {
        httpParams.setParameter(AllClientPNames.LOCAL_ADDRESS, socketLocalAddress);
    }

    if (socketTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);
    }

    httpParams.setIntParameter(AllClientPNames.SOCKET_BUFFER_SIZE, socketBufferSize);

    if (connectionTimeout > 0) {
        httpParams.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout);
    }

    httpParams.setBooleanParameter(AllClientPNames.STALE_CONNECTION_CHECK, connectionStalecheck);

    if (connectionProxyHost != null) {
        final HttpHost proxyHost = new HttpHost(connectionProxyHost, connectionProxyPort);
        httpParams.setParameter(AllClientPNames.DEFAULT_PROXY, proxyHost);

        if (connectionProxyUsername != null && connectionProxyPassword != null) {
            final CredentialsProvider credProvider = client.getCredentialsProvider();
            credProvider.setCredentials(new AuthScope(connectionProxyHost, connectionProxyPort),
                    new UsernamePasswordCredentials(connectionProxyUsername, connectionProxyPassword));
        }
    }

    httpParams.setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, httpFollowRedirects);

    httpParams.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, httpContentCharSet);

    return client;
}

From source file:com.shonshampain.streamrecorder.util.StreamProxy.java

private HttpResponse download(String url) {
    DefaultHttpClient seed = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry);
    final DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
    final HttpGet method = new HttpGet(url);
    method.addHeader("Icy-MetaData", "1");
    HttpResponse response;//  w  w  w .  ja v a2  s.c o m
    Logger.d(DBG, TAG, "starting download");
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Callable<HttpResponse> readTask = new Callable<HttpResponse>() {
        @Override
        public HttpResponse call() throws Exception {
            return http.execute(method);
        }
    };
    Future<HttpResponse> future = executor.submit(readTask);
    try {
        response = future.get(STREAM_STALLED_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (TimeoutException to) {
        return null;
    } catch (InterruptedException ie) {
        Logger.e(TAG, "The read operation was interrupted");
        return null;
    } catch (ExecutionException ee) {
        return null;
    }
    Logger.d(DBG, TAG, "downloaded");
    return response;
}

From source file:com.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java

private void setHostNameVerifierAndRoutePlanner(DefaultHttpClient httpClient) {

    // Use custom HostVerifier to accept our wildcard SSL Certificates: *.etilbudsavis.dk
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", socketFactory, 443));
    SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry);

    httpClient = new DefaultHttpClient(mgr, httpClient.getParams());

    // Change RoutePlanner to avoid SchemeRegistry causing IllegalStateException.
    // Some devices with faults in their default route planner
    httpClient.setRoutePlanner(new DefaultHttpRoutePlanner(registry));

    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

}

From source file:com.andybotting.tramhunter.service.TramTrackerServiceJSON.java

/**
 * Fetch JSON data over HTTP/*from www . j a  v a 2  s.c om*/
 * @throws TramTrackerServiceException 
 */
public InputStream getJSONData(String url) throws TramTrackerServiceException {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // Set the user agent
    String packageName = "Unknown";
    String packageVersion = "Unknown";

    try {
        packageName = mContext.getPackageName();
        PackageInfo pi = mContext.getPackageManager().getPackageInfo(packageName, 0);
        packageVersion = pi.versionName;
    } catch (NameNotFoundException e) {
        // Nope
    }

    httpClient.getParams().setParameter("http.useragent", packageName + " " + packageVersion);

    URI uri;
    InputStream data = null;
    try {
        uri = new URI(url);
        HttpGet method = new HttpGet(uri);
        HttpResponse response = httpClient.execute(method);
        data = response.getEntity().getContent();
    } catch (Exception e) {
        throw new TramTrackerServiceException(e);
    }

    return data;
}

From source file:com.naryx.tagfusion.cfm.xml.ws.javaplatform.DynamicWebServiceStubGenerator.java

@SuppressWarnings("deprecation")
private String getWSDLContents(String wsdlURL, CallParameters cp) throws cfmRunTimeException {
    try {/* w ww  .jav a 2  s . c om*/
        String wsdlL = wsdlURL.toLowerCase();
        String contents = null;
        if (wsdlL.startsWith("<?xml version")) {
            // The location is the WSDL itself (unexpected)
            contents = wsdlURL;
        } else {
            InputStream is = null;
            InputStreamReader isr = null;
            StringBuilder buffy = null;
            HttpGet method = null;
            try {
                if (wsdlL.startsWith("http:") || wsdlL.startsWith("https:")) {
                    // Read from network
                    DefaultHttpClient client = new DefaultHttpClient();

                    // Set the timeout
                    int timeout = cp.getTimeout();
                    client.getParams().setParameter("http.connection.timeout", timeout);
                    client.getParams().setParameter("http.socket.timeout", timeout);

                    if (cp.getUsername() != null || cp.getPassword() != null) {
                        // Set any credentials
                        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                                new UsernamePasswordCredentials(cp.getUsername(), cp.getPassword()));
                    }

                    if (cp.getProxyServer() != null) {
                        // Set the proxy
                        HttpHost proxy = new HttpHost(cp.getProxyServer(),
                                (cp.getProxyPort() == -1) ? cp.getDefaultProxyPort() : cp.getProxyPort());
                        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                        if (cp.getProxyUser() != null || cp.getProxyPassword() != null) {
                            // Set the proxy credentials
                            client.getCredentialsProvider().setCredentials(
                                    new AuthScope(cp.getProxyServer(), cp.getProxyPort()),
                                    new UsernamePasswordCredentials(cp.getProxyUser(), cp.getProxyPassword()));

                        }
                    }

                    // Create the method and get the response
                    method = new HttpGet(wsdlURL);
                    client.getParams().setParameter("http.protocol.handle-redirects", true);
                    HttpResponse response = client.execute(method);
                    switch (response.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL
                                                + ". Proxy authentication is required.",
                                        response.getStatusLine().toString()));
                    case HttpStatus.SC_UNAUTHORIZED:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL + ". Authentication is required.",
                                        response.getStatusLine().toString()));
                    case HttpStatus.SC_USE_PROXY:
                        throw new cfmRunTimeException(
                                catchDataFactory.extendedException("errorCode.runtimeError",
                                        "Failed to access WSDL: " + wsdlURL
                                                + ". The use of a proxy is required.",
                                        response.getStatusLine().toString()));
                    }
                    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                        throw new cfmRunTimeException(catchDataFactory.extendedException(
                                "errorCode.runtimeError", "Failed to access WSDL: " + wsdlURL,
                                response.getStatusLine().toString()));
                    is = response.getEntity().getContent();
                } else {
                    // Just try to read off disk
                    File f = new File(wsdlURL);
                    is = new FileInputStream(f);
                }

                // Read the data
                char[] buf = new char[4096];
                int read = -1;
                buffy = new StringBuilder();
                isr = new InputStreamReader(is);
                while ((read = isr.read(buf, 0, buf.length)) != -1)
                    buffy.append(buf, 0, read);
                contents = buffy.toString();
            } finally {
                if (isr != null)
                    isr.close();
                if (is != null)
                    is.close();
                if (method != null)
                    method.releaseConnection();
            }
        }

        // Calc the sum and return
        return contents;
    } catch (IOException ex) {
        throw new cfmRunTimeException(
                catchDataFactory.generalException("errorCode.runtimeError", "Failed to access WSDL located at "
                        + wsdlURL + ". There may be an error in the target WSDL. " + ex.getMessage()));
    }
}

From source file:com.google.acre.script.AcreFetch.java

@SuppressWarnings("boxing")
public void fetch(boolean system, String response_encoding, boolean log_to_user, boolean no_redirect) {

    if (request_url.length() > 2047) {
        throw new AcreURLFetchException("fetching URL failed - url is too long");
    }/*  w  w w.j a v  a  2 s. c o  m*/

    DefaultHttpClient client = new DefaultHttpClient(_connectionManager, null);

    HttpParams params = client.getParams();

    // pass the deadline down to the invoked service.
    // this will be ignored unless we are fetching from another
    // acre server.
    // note that we may send a deadline that is already passed:
    // it's not our job to throw here since we don't know how
    // the target service will interpret the quota header.
    // NOTE: this is done *after* the user sets the headers to overwrite
    // whatever settings they might have tried to change for this value
    // (which could be a security hazard)
    long sub_deadline = (HostEnv.LIMIT_EXECUTION_TIME) ? _deadline - HostEnv.SUBREQUEST_DEADLINE_ADVANCE
            : System.currentTimeMillis() + HostEnv.ACRE_URLFETCH_TIMEOUT;
    int reentries = _reentries + 1;
    request_headers.put(HostEnv.ACRE_QUOTAS_HEADER, "td=" + sub_deadline + ",r=" + reentries);

    // if this is not an internal call, we need to invoke the call thru a proxy
    if (!_internal) {
        // XXX No sense wasting the resources to gzip inside the network.
        // XXX seems that twitter gets upset when we do this
        /*
        if (!request_headers.containsKey("accept-encoding")) {
        request_headers.put("accept-encoding", "gzip");
        }
        */
        String proxy_host = Configuration.Values.HTTP_PROXY_HOST.getValue();
        int proxy_port = -1;
        if (!(proxy_host.length() == 0)) {
            proxy_port = Configuration.Values.HTTP_PROXY_PORT.getInteger();
            HttpHost proxy = new HttpHost(proxy_host, proxy_port, "http");
            params.setParameter(AllClientPNames.DEFAULT_PROXY, proxy);
        }
    }

    params.setParameter(AllClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    // in msec

    long timeout = _deadline - System.currentTimeMillis();
    if (timeout < 0)
        timeout = 0;
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, (int) timeout);
    params.setParameter(AllClientPNames.SO_TIMEOUT, (int) timeout);

    // we're not streaming the request so this should be a win.
    params.setParameter(AllClientPNames.TCP_NODELAY, true);

    // reuse an existing socket if it is in TIME_WAIT state.
    params.setParameter(AllClientPNames.SO_REUSEADDR, true);

    // set the encoding of our POST payloads to UTF-8
    params.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    BasicCookieStore cstore = new BasicCookieStore();
    for (AcreCookie cookie : request_cookies.values()) {
        cstore.addCookie(cookie.toClientCookie());
    }
    client.setCookieStore(cstore);

    HttpRequestBase method;

    HashMap<String, String> logmsg = new HashMap<String, String>();
    logmsg.put("Method", request_method);
    logmsg.put("URL", request_url);

    params.setParameter(AllClientPNames.HANDLE_REDIRECTS, !no_redirect);
    logmsg.put("Redirect", Boolean.toString(!no_redirect));

    try {
        if (request_method.equals("GET")) {
            method = new HttpGet(request_url);
        } else if (request_method.equals("POST")) {
            method = new HttpPost(request_url);
        } else if (request_method.equals("HEAD")) {
            method = new HttpHead(request_url);
        } else if (request_method.equals("PUT")) {
            method = new HttpPut(request_url);
        } else if (request_method.equals("DELETE")) {
            method = new HttpDelete(request_url);
        } else if (request_method.equals("PROPFIND")) {
            method = new HttpPropFind(request_url);
        } else {
            throw new AcreURLFetchException("Failed: unsupported (so far) method " + request_method);
        }
        method.getParams().setBooleanParameter(AllClientPNames.USE_EXPECT_CONTINUE, false);
    } catch (java.lang.IllegalArgumentException e) {
        throw new AcreURLFetchException("Unable to fetch URL; this is most likely an issue with URL encoding.");
    } catch (java.lang.IllegalStateException e) {
        throw new AcreURLFetchException("Unable to fetch URL; possibly an illegal protocol?");
    }

    StringBuilder request_header_log = new StringBuilder();
    for (Map.Entry<String, String> header : request_headers.entrySet()) {
        String key = header.getKey();
        String value = header.getValue();

        // XXX should suppress cookie headers?
        // content-type and length?

        if ("content-type".equalsIgnoreCase(key)) {
            Matcher m = contentTypeCharsetPattern.matcher(value);
            if (m.find()) {
                content_type = m.group(1);
                content_type_charset = m.group(2);
            } else {
                content_type_charset = "utf-8";
            }
            method.addHeader(key, value);
        } else if ("content-length".equalsIgnoreCase(key)) {
            // ignore user-supplied content-length, which is
            // probably wrong due to chars vs bytes and is
            // redundant anyway
            ArrayList<String> msg = new ArrayList<String>();
            msg.add("User-supplied content-length header is ignored");
            _acre_response.log("warn", msg);
        } else if ("user-agent".equalsIgnoreCase(key)) {
            params.setParameter(AllClientPNames.USER_AGENT, value);
        } else {
            method.addHeader(key, value);
        }
        if (!("x-acre-auth".equalsIgnoreCase(key))) {
            request_header_log.append(key + ": " + value + "\r\n");
        }
    }
    logmsg.put("Headers", request_header_log.toString());

    // XXX need more detailed error checking
    if (method instanceof HttpEntityEnclosingRequestBase && request_body != null) {

        HttpEntityEnclosingRequestBase em = (HttpEntityEnclosingRequestBase) method;
        try {
            if (request_body instanceof String) {
                StringEntity ent = new StringEntity((String) request_body, content_type_charset);
                em.setEntity(ent);
            } else if (request_body instanceof JSBinary) {
                ByteArrayEntity ent = new ByteArrayEntity(((JSBinary) request_body).get_data());
                em.setEntity(ent);
            }
        } catch (UnsupportedEncodingException e) {
            throw new AcreURLFetchException(
                    "Failed to fetch URL. " + " - Unsupported charset: " + content_type_charset);
        }
    }

    if (!system && log_to_user) {
        ArrayList<Object> msg = new ArrayList<Object>();
        msg.add("urlfetch request");
        msg.add(logmsg);
        _acre_response.log("debug", msg);
    }
    _logger.info("urlfetch.request", logmsg);

    long startTime = System.currentTimeMillis();

    try {
        // this sends the http request and waits
        HttpResponse hres = client.execute(method);
        status = hres.getStatusLine().getStatusCode();
        HashMap<String, String> res_logmsg = new HashMap<String, String>();
        res_logmsg.put("URL", request_url);
        res_logmsg.put("Status", ((Integer) status).toString());

        Header content_type_header = null;

        // translate response headers
        StringBuilder response_header_log = new StringBuilder();
        Header[] rawheaders = hres.getAllHeaders();
        for (Header rawheader : rawheaders) {
            String headername = rawheader.getName().toLowerCase();
            if (headername.equalsIgnoreCase("content-type")) {
                content_type_header = rawheader;
                // XXX should strip everything after ;
                content_type = rawheader.getValue();

                // XXX don't set content_type_parameters, deprecated?
            } else if (headername.equalsIgnoreCase("x-metaweb-cost")) {
                _costCollector.merge(rawheader.getValue());
            } else if (headername.equalsIgnoreCase("x-metaweb-tid")) {
                res_logmsg.put("ITID", rawheader.getValue());
            }

            headers.put(headername, rawheader.getValue());
            response_header_log.append(headername + ": " + rawheader.getValue() + "\r\n");
        }

        res_logmsg.put("Headers", response_header_log.toString());

        if (!system && log_to_user) {
            ArrayList<Object> msg = new ArrayList<Object>();
            msg.add("urlfetch response");
            msg.add(res_logmsg);
            _acre_response.log("debug", msg);
        }

        _logger.info("urlfetch.response", res_logmsg);

        // read cookies
        for (Cookie c : cstore.getCookies()) {
            cookies.put(c.getName(), new AcreCookie(c));
        }

        // get body encoding

        String charset = null;
        if (content_type_header != null) {
            HeaderElement values[] = content_type_header.getElements();
            if (values.length == 1) {
                NameValuePair param = values[0].getParameterByName("charset");
                if (param != null) {
                    charset = param.getValue();
                }
            }
        }

        if (charset == null)
            charset = response_encoding;

        // read body
        HttpEntity ent = hres.getEntity();
        if (ent != null) {
            InputStream res_stream = ent.getContent();
            Header cenc = ent.getContentEncoding();
            if (cenc != null && res_stream != null) {
                HeaderElement[] codecs = cenc.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        res_stream = new GZIPInputStream(res_stream);
                    }
                }
            }

            long firstByteTime = 0;
            long endTime = 0;
            if (content_type != null
                    && (content_type.startsWith("image/") || content_type.startsWith("application/octet-stream")
                            || content_type.startsWith("multipart/form-data"))) {
                // HttpClient's InputStream doesn't support mark/reset, so
                // wrap it with one that does.
                BufferedInputStream bufis = new BufferedInputStream(res_stream);
                bufis.mark(2);
                bufis.read();
                firstByteTime = System.currentTimeMillis();
                bufis.reset();
                byte[] data = IOUtils.toByteArray(bufis);

                endTime = System.currentTimeMillis();
                body = new JSBinary();
                ((JSBinary) body).set_data(data);

                try {
                    if (res_stream != null) {
                        res_stream.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            } else if (res_stream == null || charset == null) {
                firstByteTime = endTime = System.currentTimeMillis();
                body = "";
            } else {
                StringWriter writer = new StringWriter();
                Reader reader = new InputStreamReader(res_stream, charset);
                int i = reader.read();
                firstByteTime = System.currentTimeMillis();
                writer.write(i);
                IOUtils.copy(reader, writer);
                endTime = System.currentTimeMillis();
                body = writer.toString();

                try {
                    reader.close();
                    writer.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            long waitingTime = firstByteTime - startTime;
            long readingTime = endTime - firstByteTime;

            _logger.debug("urlfetch.timings", "waiting time: " + waitingTime + "ms");
            _logger.debug("urlfetch.timings", "reading time: " + readingTime + "ms");

            Statistics.instance().collectUrlfetchTime(startTime, firstByteTime, endTime);

            _costCollector.collect((system) ? "asuc" : "auuc").collect((system) ? "asuw" : "auuw", waitingTime)
                    .collect((system) ? "asub" : "auub", waitingTime);
        }
    } catch (IllegalArgumentException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("failed to fetch URL. " + " - Request Error: " + cause.getMessage());
    } catch (IOException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } catch (RuntimeException e) {
        Throwable cause = e.getCause();
        if (cause == null)
            cause = e;
        throw new AcreURLFetchException("Failed to fetch URL. " + " - Network Error: " + cause.getMessage());
    } finally {
        method.abort();
    }
}

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   ww  w  . j  a v a  2 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.wikilab.android.friendica01.TwAjax.java

private void runDefault() throws IOException {
    Log.v("TwAjax", "runDefault URL=" + myUrl);

    // Create a new HttpClient and Get/Post Header
    DefaultHttpClient httpclient = getNewHttpClient();
    setHttpClientProxy(httpclient);//w  w  w  . jav a2s. c  om
    httpclient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    //final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(httpclient.getParams(), false);

    HttpRequestBase m;
    if (myMethod == "POST") {
        m = new HttpPost(myUrl);
        ((HttpPost) m).setEntity(new UrlEncodedFormEntity(myPostData, "utf-8"));
    } else {
        m = new HttpGet(myUrl);
    }
    m.addHeader("Host", m.getURI().getHost());
    if (twSession != null)
        m.addHeader("Cookie", "twnetSID=" + twSession);
    httpclient.setCookieStore(cookieStoreManager);

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        m.addHeader("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    // Execute HTTP Get/Post Request
    HttpResponse response = httpclient.execute(m);
    //InputStream is = response.getEntity().getContent();
    myHttpStatus = response.getStatusLine().getStatusCode();
    if (this.fetchHeader != null) {
        this.fetchHeaderResult = response.getHeaders(this.fetchHeader);
        Header[] h = response.getAllHeaders();
        for (Header hh : h)
            Log.d(TAG, "Header " + hh.getName() + "=" + hh.getValue());

    } else if (this.downloadToFile != null) {
        Log.v("TwAjax", "runDefault downloadToFile=" + downloadToFile);
        // download the file
        InputStream input = new BufferedInputStream(response.getEntity().getContent());
        OutputStream output = new FileOutputStream(downloadToFile);

        byte data[] = new byte[1024];

        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            //publishProgress((int)(total*100/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } else if (this.convertToBitmap) {
        myBmpResult = BitmapFactory.decodeStream(response.getEntity().getContent());
    } else if (this.convertToXml) {
        try {
            myXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(response.getEntity().getContent());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }

    } else {
        myResult = EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    //BufferedInputStream bis = new BufferedInputStream(is);
    //ByteArrayBuffer baf = new ByteArrayBuffer(50);

    //int current = 0;
    //while((current = bis.read()) != -1){
    //    baf.append((byte)current);
    //}

    //myResult = new String(baf.toByteArray(), "utf-8");
    success = true;
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * Convenience method for sending HTTP requests.
 * <b><span style="color:red">Note</span></b>: This method is intended to be
 * used internally, not by end-users./*  www . j  ava  2 s  . c  o m*/
 * 
 * @param baseURL - <b>Example</b>: http://minus.com/api
 * @param parametersBody - The parameters (name => value pairs) to pass to
 *            the request.
 * @param sessionId - If <tt>null</tt> or empty, then create and use a new
 *            session, otherwise, use the specified session_id (which is
 *            stored in a cookie).
 * @param requestType
 * @param additionalRequestHeaders -
 * @param expectedResponseType
 * @return The response retrieved from Minus API.
 * @throws MinusException
 */
private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders,
        final ExpectedResponseType expectedResponseType) throws MinusException {

    DefaultHttpClient client = null;
    HttpRequestBase request = null;
    InputStream responseContent = null;
    boolean errorOccured = false;

    try {
        if (requestType == RequestType.GET) {
            request = new HttpGet(baseURL);
            if (parametersBody != null && !parametersBody.isEmpty()) {
                request = appendParametersToRequest(request, parametersBody);
            }

        } else if (requestType == RequestType.POST) {
            UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody),
                    HTTP.UTF_8);
            request = new HttpPost(baseURL);
            ((HttpPost) request).setEntity(encodedEntity);

        } else {
            throw new MinusException("The method (" + requestType + ") is unknown, weird ...");
        }

        request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT));
        if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) {
            for (Header aHeader : additionalRequestHeaders) {
                request.addHeader(aHeader);
            }
        }

        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);

        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // Execute the request ... pass local context as a parameter
        HttpResponse resp = client.execute(request, localContext);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        Object result = null;
        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                if (expectedResponseType == ExpectedResponseType.STRING) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) {
                    result = entity;
                }
            }
        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result, sessionCookie);

    } catch (Exception e) {
        errorOccured = true;
        if (request != null) {
            request.abort();
        }
        String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            // We must not close the client is the expected response is an
            // InputStream. Indeed, if ever we close the client, we won't be
            // able to read the response because of SocketException.
            if (errorOccured) {
                client.getConnectionManager().shutdown();
            } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) {
                client.getConnectionManager().shutdown();
            }
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:com.expressui.domain.RestClientService.java

/**
 * Create a REST client//  w  w  w . j  a  va  2 s . co  m
 *
 * @param uri   uri of the service
 * @param clazz client class
 * @param <T>   class type
 * @return REST client
 * @throws Exception
 */
public <T> T create(String uri, Class<T> clazz) throws Exception {
    RestClientProxyFactoryBean restClientFactory = new RestClientProxyFactoryBean();
    restClientFactory.setBaseUri(new URI(uri));
    restClientFactory.setServiceInterface(clazz);
    if (applicationProperties.getHttpProxyHost() != null && applicationProperties.getHttpProxyPort() != null) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpHost proxy = new HttpHost(applicationProperties.getHttpProxyHost(),
                applicationProperties.getHttpProxyPort());

        if (applicationProperties.getHttpProxyUsername() != null
                && applicationProperties.getHttpProxyPassword() != null) {

            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(applicationProperties.getHttpProxyHost(),
                            applicationProperties.getHttpProxyPort()),
                    new UsernamePasswordCredentials(applicationProperties.getHttpProxyUsername(),
                            applicationProperties.getHttpProxyPassword()));
        }

        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        restClientFactory.setHttpClient(httpClient);
    }
    restClientFactory.afterPropertiesSet();
    return (T) restClientFactory.getObject();
}