Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

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

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata_last2month(String SENSOR_KEY, String SENSOR_TOKEN)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    /*/* w  w w.  ja v  a 2s. c  o m*/
     * Get local UTC time (now) to request data to server
     */
    //TODO verify with Bart if shall request UTC or local time (guessed UTC)
    Date d = new Date(); // already return UTC
    //long moja_data = d.getTime() - (d.getTimezoneOffset() * 60 * 1000); // calculate
    // data/time
    // (milliseconds)
    // at local timzone
    //d.setTime(moja_data);

    d.setHours(00);
    d.setSeconds(00);
    d.setMinutes(00);

    HttpResponse response = null;
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet(
                "https://" + api_server_ip + "/sensor/" + SENSOR_KEY + "?version=1.0&token=" + SENSOR_TOKEN
                        + "&start=" + ((d.getTime() / 1000) - 5184000) + "&resolution=day&unit=watt"));

        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:dev.memento.MainActivity.java

/**
 * Make http requests to the Timegate at the proxy server to obtain a Memento 
 * and its TimeMap.  This is done in a background thread so the UI is not locked up.
 * If an error occurs, mErrorMessage is set to an error message which is shown
 * to the user.//from w w w. jav  a 2 s  . com
 * @param initUrl The URL whose Memento is to be discovered
 * @param loadMemento Set to true if you want the Memento discovered to be loaded
 * into the web browser.
 */
private void makeHttpRequests(String initUrl, boolean loadMemento) {

    // Contact Memento proxy with chosen Accept-Datetime:
    // http://mementoproxy.lanl.gov/aggr/timegate/http://example.com/
    // Accept-Datetime: Tue, 24 Jul 2001 15:45:04 GMT             

    HttpClient httpclient = new DefaultHttpClient();

    // Disable automatic redirect handling so we can process the 302 ourself 
    httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);

    String url = mDefaultTimegateUri + initUrl;
    HttpGet httpget = new HttpGet(url);

    // Change the request date to 23:00:00 if this is the first memento.
    // Otherwise we'll be out of range.

    String acceptDatetime;

    if (mFirstMemento != null && mFirstMemento.getDateTime().equals(mDateChosen)) {
        if (Log.LOG)
            Log.d(LOG_TAG, "Changing chosen time to 23:59 since datetime matches first Memento.");
        SimpleDateTime dt = new SimpleDateTime(mDateChosen);
        dt.setToLastHour();
        acceptDatetime = dt.longDateFormatted();
    } else {
        acceptDatetime = mDateChosen.longDateFormatted();
    }

    httpget.setHeader("Accept-Datetime", acceptDatetime);
    httpget.setHeader("User-Agent", mUserAgent);

    if (Log.LOG)
        Log.d(LOG_TAG, "Accessing: " + httpget.getURI());
    if (Log.LOG)
        Log.d(LOG_TAG, "Accept-Datetime: " + acceptDatetime);

    HttpResponse response = null;
    try {
        response = httpclient.execute(httpget);

        if (Log.LOG)
            Log.d(LOG_TAG, "Response code = " + response.getStatusLine());

    } catch (Exception e) {
        mErrorMessage = "Sorry, we are having problems contacting the server. Please " + "try again later.";
        if (Log.LOG)
            Log.e(LOG_TAG, Utilities.getExceptionStackTraceAsString(e));
        return;
    } finally {
        // Deallocate all system resources
        httpclient.getConnectionManager().shutdown();
    }

    // Get back:
    // 300 (TCN: list with multiple Mementos to choose from)
    // or 302 (TCN: choice) 
    // or 404 (no Mementos for this URL)
    // or 406 (TCN: list with only first and last Mementos)

    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == 300) {
        // TODO: Implement.  Right now the lanl proxy doesn't appear to be returning this
        // code, so let's just ignore it for now.
        if (Log.LOG)
            Log.d(LOG_TAG, "Pick a URL from list - NOT IMPLEMENTED");
    } else if (statusCode == 302) {
        // Send browser to Location header URL
        // Note that the date/time of this memento is not given in the Location but can
        // be found when parsing the Link header.

        Header[] headers = response.getHeaders("Location");
        if (headers.length == 0) {
            mErrorMessage = "Sorry, but there was an unexpected error that will "
                    + "prevent the Memento from being displayed. Try again in 5 minutes.";
            if (Log.LOG)
                Log.e(LOG_TAG, "Error: Location header not found in response headers.");
        } else {
            final String redirectUrl = headers[0].getValue();

            // We can't update the view directly since we're running
            // in a thread, so use mUpdateResults to show a toast message
            // if accessing a different date than what was requested.

            //mHandler.post(mUpdateResults);

            // Parse various Links
            headers = response.getHeaders("Link");
            if (headers.length == 0) {
                if (Log.LOG)
                    Log.e(LOG_TAG, "Error: Link header not found in response headers.");
                mErrorMessage = "Sorry, but the Memento could not be accessed. Try again in 5 minutes.";
            } else {
                String linkValue = headers[0].getValue();

                mTimeMaps.clear();
                mTimeBundle = null;
                mMementos.clear();

                // Get the datetime of this mememnto which should be supplied in the
                // Link: headers
                // Do not add the mementos to the global list of mementos because
                // the global list will be created when we process the timemap later.
                Memento memento = parseCsvLinks(linkValue, false);

                if (loadMemento) {
                    mDateDisplayed = memento.getDateTime();
                    if (Log.LOG)
                        Log.v(LOG_TAG, "Closest to " + mDateChosen + " is " + mDateDisplayed);

                    if (Log.LOG)
                        Log.d(LOG_TAG, "Redirecting browser to " + redirectUrl);
                    mCurrentMemento = memento;

                    // Can't call WebView methods except on UI thread!
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            surfToUrl(redirectUrl);
                        }
                    });

                    // Now that we know the date, update the UI to reflect it
                    mHandler.post(mUpdateResults);
                }

                if (mTimeMaps.size() > 0)
                    if (!accessTimeMap() && mErrorMessage == null)
                        mErrorMessage = "There were problems accessing the Memento's TimeMap. "
                                + "Please try again later.";
            }
        }
    } else if (statusCode == 404) {
        if (Log.LOG)
            Log.d(LOG_TAG, "Received 404 from proxy so no mementos for " + initUrl);
        mErrorMessage = "Sorry, there are no Mementos for this web page.";
    } else if (statusCode == 406) {

        // Parse various Links
        Header[] headers = response.getHeaders("Link");

        if (headers.length == 0) {
            if (Log.LOG)
                Log.d(LOG_TAG, "Error: Link header not found in 406 response headers.");
            //mErrorMessage = "Sorry, but there was an error in retreiving this Memento.";

            // The lanl proxy has it wrong.  It should return 404 when the URL is not
            // present, so we'll just pretend this is a 404.
            mErrorMessage = "Sorry, but there are no Mementos for this URL.";
        } else {
            String linkValue = headers[0].getValue();

            mTimeMaps.clear();
            mTimeBundle = null;
            mMementos.clear();

            parseCsvLinks(linkValue, false);

            if (mTimeMaps.size() > 0)
                accessTimeMap();

            if (mFirstMemento == null || mLastMemento == null) {
                if (Log.LOG)
                    Log.e(LOG_TAG, "Could not find first or last Memento in 406 response for " + url);
                mErrorMessage = "Sorry, but there was an error in retreiving this Memento.";
            } else {
                if (Log.LOG)
                    Log.d(LOG_TAG, "Not available in this date range (" + mFirstMemento.getDateTimeSimple()
                            + " to " + mLastMemento.getDateTimeSimple() + ")");

                // According to Rob Sanderson (LANL), we will only get 406 when the date is too
                // early, so redirect to first Memento

                mDateDisplayed = new SimpleDateTime(mFirstMemento.getDateTime());
                final String redirectUrl = mFirstMemento.getUrl();
                if (Log.LOG)
                    Log.d(LOG_TAG, "Loading memento " + redirectUrl);

                // Can't call WebView methods except on UI thread!
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        surfToUrl(redirectUrl);
                    }
                });

                mHandler.post(mUpdateResults);
            }
        }
    } else {
        mErrorMessage = "Sorry, but there was an unexpected error that will "
                + "prevent the Memento from being displayed. Try again in 5 minutes.";
        if (Log.LOG)
            Log.e(LOG_TAG, "Unexpected response code in makeHttpRequests = " + statusCode);
    }
}

From source file:org.madsonic.service.SettingsService.java

private void validateLicense() {
    String email = getLicenseEmail();
    Date date = getLicenseDate();

    if (email == null || date == null) {
        licenseValidated = false;//  w w  w. ja va  2 s .c  o  m
        return;
    }

    licenseValidated = true;

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 120000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 120000);
    HttpGet method = new HttpGet(
            "http://subsonic.org/backend/validateLicense.view" + "?email=" + StringUtil.urlEncode(email)
                    + "&date=" + date.getTime() + "&version=" + versionService.getLocalVersion());
    try {
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String content = client.execute(method, responseHandler);
        licenseValidated = content != null && content.contains("true");
        if (!licenseValidated) {
            LOG.warn("License key is not valid.");
        }
        String[] lines = StringUtils.split(content);
        if (lines.length > 1) {
            licenseExpires = new Date(Long.parseLong(lines[1]));
        }

    } catch (Throwable x) {
        LOG.warn("Failed to validate license.", x);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.eclipse.skalli.core.destination.DestinationComponent.java

private void setProxy(HttpClient client, URL url) {
    if (isLocalDomain(url)) {
        return;/*w ww .ja v a  2 s.c o  m*/
    }

    String protocol = url.getProtocol();

    // use the system properties as default
    String defaultProxyHost = System.getProperty(HTTP_PROXY_HOST);
    String defaultProxyPort = System.getProperty(HTTP_PROXY_PORT);
    String proxyHost = HTTPS.equals(protocol) ? System.getProperty(HTTPS_PROXY_HOST, defaultProxyHost)
            : defaultProxyHost;
    int proxyPort = NumberUtils.toInt(
            HTTPS.equals(protocol) ? System.getProperty(HTTPS_PROXY_PORT, defaultProxyPort) : defaultProxyPort);
    String nonProxyHosts = System.getProperty(NON_PROXY_HOSTS, StringUtils.EMPTY);

    // allow to overwrite the system properties with configuration /api/config/proxy
    if (configService != null) {
        ProxyConfig proxyConfig = configService.readConfiguration(ProxyConfig.class);
        if (proxyConfig != null) {
            String defaultConfigProxyHost = proxyConfig.getHost();
            String defaultConfigProxyPort = proxyConfig.getPort();
            String configProxyHost = HTTPS.equals(protocol) ? proxyConfig.getHostSSL() : defaultConfigProxyHost;
            int configProxyPort = NumberUtils
                    .toInt(HTTPS.equals(protocol) ? proxyConfig.getPortSSL() : defaultConfigProxyPort);
            if (StringUtils.isNotBlank(configProxyHost) && configProxyPort > 0) {
                proxyHost = configProxyHost;
                proxyPort = configProxyPort;
            }
            String configNonProxyHosts = proxyConfig.getNonProxyHosts();
            if (StringUtils.isNotBlank(configNonProxyHosts)) {
                nonProxyHosts = configNonProxyHosts;
            }
        }
    }

    // sanitize the nonProxyHost pattern (remove whitespace etc.)
    if (StringUtils.isNotBlank(nonProxyHosts)) {
        nonProxyHosts = StringUtils.replaceEach(StringUtils.deleteWhitespace(nonProxyHosts), RE_SEARCH,
                RE_REPLACE);
    }

    if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0 && !Pattern.matches(nonProxyHosts, url.getHost())) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort, HTTP);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
}

From source file:com.pari.ic.ICManager.java

public DefaultHttpClient getSecuredHttpClient(HttpClient httpClient) throws Exception {
    final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
    try {/*from w ww.j a  v  a  2s . c o m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return _AcceptedIssuers;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
        };
        ctx.init(null, new TrustManager[] { tm }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = httpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
        return new DefaultHttpClient(ccm, httpClient.getParams());
    } catch (Exception e) {
        throw e;
    }
}