Example usage for org.apache.http.params HttpConnectionParams setConnectionTimeout

List of usage examples for org.apache.http.params HttpConnectionParams setConnectionTimeout

Introduction

In this page you can find the example usage for org.apache.http.params HttpConnectionParams setConnectionTimeout.

Prototype

public static void setConnectionTimeout(HttpParams httpParams, int i) 

Source Link

Usage

From source file:com.emc.vipr.ribbon.ViPRDataServicesServerList.java

@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
    protocol = clientConfig.getPropertyAsString(SmartClientConfigKey.ViPRDataServicesProtocol, "")
            .toLowerCase();/*  w w  w .j  a v  a  2  s.  c  om*/
    if (!Arrays.asList("http", "https").contains(protocol))
        throw new IllegalArgumentException("Invalid protocol: " + protocol);

    String nodeStr = clientConfig.getPropertyAsString(SmartClientConfigKey.ViPRDataServicesInitialNodes, "");
    if (nodeStr.trim().length() == 0)
        throw new IllegalStateException("No servers configured in smartConfig or NIWS config");
    setNodeList(SmartClientConfig.parseServerList(nodeStr));

    // pull the port from the initial node list (it will not be returned by the list-data-nodes call)
    port = getNodeList().get(0).getPort();

    user = clientConfig.getPropertyAsString(SmartClientConfigKey.ViPRDataServicesUser, null);

    secret = clientConfig.getPropertyAsString(SmartClientConfigKey.ViPRDataServicesUserSecret, null);

    int timeout = clientConfig.getPropertyAsInteger(SmartClientConfigKey.ViPRDataServicesTimeout,
            SmartClientConfig.DEFAULT_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), timeout);
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), timeout);

    if (logger.isDebugEnabled()) {
        logger.debug("Configured node enumeration");
        logger.debug("--- protocol: " + protocol);
        logger.debug("--- nodeList: " + getNodeList());
        logger.debug("--- user: " + user);
        logger.debug("--- secret: " + secret);
        logger.debug("--- timeout: " + timeout);
        logger.debug("--- httpClient: " + (httpClient != null));
    }
}

From source file:com.tomgibara.android.veecheck.VeecheckThread.java

private VeecheckResult performRequest(VeecheckVersion version, String uri)
        throws ClientProtocolException, IOException, IllegalStateException, SAXException {
    HttpClient client = new DefaultHttpClient();
    // TODO ideally it should be possible to adjust these constants
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
    HttpGet request = new HttpGet(version.substitute(uri));
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    try {//from w  w  w . j  a va  2 s . co m
        StatusLine line = response.getStatusLine();
        // TODO this is lazy, we should consider other codes here
        if (line.getStatusCode() != 200) {
            throw new IOException("Request failed: " + line.getReasonPhrase());
        }
        Header header = response.getFirstHeader(HTTP.CONTENT_TYPE);
        Encoding encoding = identityEncoding(header);
        VeecheckResult handler = new VeecheckResult(version);
        Xml.parse(entity.getContent(), encoding, handler);
        return handler;
    } finally {
        entity.consumeContent();
    }
}

From source file:org.artags.android.app.widget.HttpUtils.java

/**
 * Generate and return a {@link HttpClient} configured for general use,
 * including setting an application-specific user-agent string.
 * @return /*from w  w  w .  ja v  a  2  s .  c  o m*/
 */
public static HttpClient getHttpClient() {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    final DefaultHttpClient client = new DefaultHttpClient(params);

    client.addRequestInterceptor(new HttpRequestInterceptor() {

        public void process(HttpRequest request, HttpContext context) {
            // Add header to accept gzip content
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    return client;
}

From source file:com.halseyburgund.roundware.server.RWHttpManager.java

public static String doPost(String page, Properties props) throws Exception {
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT_MSEC);

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    HttpResponse response = null;//from  ww w .  java  2 s .co m
    HttpEntity entity = null;

    StringBuffer sbResponse = new StringBuffer();

    Enumeration<Object> enumProps = props.keys();
    String key, value = null;

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    while (enumProps.hasMoreElements()) {
        key = (String) enumProps.nextElement();
        value = (String) props.get(key);
        nvps.add(new BasicNameValuePair(key, value));
    }

    UrlEncodedFormEntity uf = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
    request.setEntity(uf);
    request.setHeader("Content-Type", POST_MIME_TYPE);

    // Post, check and show the result (not really spectacular, but works):
    response = httpClient.execute(request);
    entity = response.getEntity();

    int status = response.getStatusLine().getStatusCode();

    // we assume that the response body contains the error message
    if (status != HttpStatus.SC_OK) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        entity.writeTo(ostream);

        RWHtmlLog.e(TAG, "Error status code = " + status, null);
        RWHtmlLog.e(TAG, ostream.toString(), null);

        throw new Exception(HTTP_POST_FAILED + status);
    } else {
        InputStream content = response.getEntity().getContent();
        // <consume response>

        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String line;

        while ((line = reader.readLine()) != null)
            sbResponse.append(line);

        content.close(); // this will also close the connection

        return sbResponse.toString();
    }
}

From source file:com.vuze.android.remote.rpc.RPC.java

public static boolean isLocalAvailable() {
    Object oldThreadPolicy = null;
    try {/*  ww  w . j a  v  a 2s  .c o m*/
        if (android.os.Build.VERSION.SDK_INT > 9) {
            // allow synchronous networking because we are only going to localhost
            // and it will return really fast (it better!)
            oldThreadPolicy = enableNasty();
        }

        String url = "http://localhost:9091/transmission/rpc?json="
                + URLEncoder.encode("{\"method\":\"session-get\"}", "utf-8");

        BasicHttpParams basicHttpParams = new BasicHttpParams();
        HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote");
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 200);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 900);
        HttpClient httpclient = new DefaultHttpClient(basicHttpParams);

        // Prepare a request object
        HttpGet httpget = new HttpGet(url); // IllegalArgumentException

        // Execute the request
        HttpResponse response = httpclient.execute(httpget);

        if (response.getStatusLine().getStatusCode() == 409) {
            // Must be RPC!
            return true;
        }

    } catch (HttpHostConnectException ignore) {
        // Connection to http://localhost:9091 refused
    } catch (Throwable e) {
        Log.e("RPC", "isLocalAvailable", e);
    } finally {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            revertNasty((ThreadPolicy) oldThreadPolicy);
        }
    }
    return false;
}

From source file:com.farru.android.volley.toolbox.HttpClientStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    /*  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(Constants.JABOND_SERVER_UID, Constants.JABOND_SERVER_PWD);
            //  w  w w .  jav a 2 s . c  om
      BasicScheme scheme = new BasicScheme();
      Header authorizationHeader = null;
      try {
    authorizationHeader = scheme.authenticate(credentials, httpRequest);
      } catch (AuthenticationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
      }
      httpRequest.addHeader(authorizationHeader);
    */ onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}

From source file:biz.mosil.webtools.MosilWeb.java

/**
 * Constructor//from  w  w  w . j a  v  a 2 s.c  o m
 * */
public MosilWeb(Context _context) {
    mHostName = "";
    mContext = _context;

    mHttpContext = new BasicHttpContext();
    mHttpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());

    mHttpParams = new BasicHttpParams();
    mHttpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    HttpConnectionParams.setConnectionTimeout(mHttpParams, MosilWebConf.CONNECT_TIME);
    HttpConnectionParams.setSoTimeout(mHttpParams, MosilWebConf.SOCKET_TIME);
}

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    HttpProtocolParams.setUseExpectContinue(globalParams, false);

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    HttpConnectionParams.setConnectionTimeout(globalParams,
            (getConfiguration().getTimeoutSeconds() + 5) * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000);

    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
    if (getConfiguration().getSocketBufferSize() != -1)
        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());

    // Only register 80, not 443 and SSL
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry);
    //clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
    //clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());

    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
                new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false));
    }/* www  .j  a  v a  2 s .  co  m*/
}

From source file:cn.dacas.emmclient.security.ssl.SslHttpStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);/*from  ww w.j  av a2s.  com*/
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    /* Register schemes, HTTP and HTTPS */
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", new PlainSocketFactory(), 80));
    registry.register(new Scheme("https", new EasySSLSocketFactory(mIsConnectingToYourServer), 443));

    /* Make a thread safe connection manager for the client */
    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParams, registry);
    HttpClient httpClient = new DefaultHttpClient(manager, httpParams);

    return httpClient.execute(httpRequest);
}

From source file:ch.cyberduck.core.http.HttpSession.java

protected AbstractHttpClient http(final String hostname) {
    if (!clients.containsKey(hostname)) {
        final HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, getEncoding());
        HttpProtocolParams.setUserAgent(params, getUserAgent());

        AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset"));

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setConnectionTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params,
                Preferences.instance().getInteger("http.socket.buffer"));
        HttpConnectionParams.setStaleCheckingEnabled(params, true);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);
        HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH);

        // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager
        HttpClientParams.setConnectionManagerTimeout(params,
                Preferences.instance().getLong("http.manager.timeout"));

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(),
                PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(),
                new SSLSocketFactory(
                        new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                        new X509HostnameVerifier() {
                            @Override
                            public void verify(String host, SSLSocket ssl) throws IOException {
                                log.warn("Hostname verification disabled for:" + host);
                            }// w  ww .  j  a  v a  2 s . co m

                            @Override
                            public void verify(String host, X509Certificate cert) throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public void verify(String host, String[] cns, String[] subjectAlts)
                                    throws SSLException {
                                log.warn("Hostname verification disabled for:" + host);
                            }

                            @Override
                            public boolean verify(String s, javax.net.ssl.SSLSession sslSession) {
                                log.warn("Hostname verification disabled for:" + s);
                                return true;
                            }
                        })));
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.get();
            if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry);
        manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total"));
        manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route"));
        AbstractHttpClient http = new DefaultHttpClient(manager, params);
        this.configure(http);
        clients.put(hostname, http);
    }
    return clients.get(hostname);
}