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.sinacloud.scs.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*  w  w w.  j a  v  a  2  s.c  om*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
@SuppressWarnings("deprecation")
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    PoolingClientConnectionManager connectionManager = ConnectionManagerFactory
            .createPoolingClientConnManager(config, httpClientParams);
    SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams);
    if (config.getMaxErrorRetry() > 0)
        httpClient.setHttpRequestRetryHandler(SdkHttpRequestRetryHandler.Singleton);
    //        httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        Scheme https = new Scheme("https", sf, 443);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new SCSClientException("Unable to access default SSL context", e);
    }

    //        /* 
    //         * If SSL cert checking for endpoints has been explicitly disabled,
    //         * register a new scheme for HTTPS that won't cause self-signed certs to
    //         * error out.
    //         */
    //        if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
    Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
    httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    //        }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        //            AmazonHttpClient.log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:com.mr.http.toolbox.MR_HttpClientStack.java

@Override
public HttpResponse performRequest(MR_Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, MR_AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);/*from w  w w.  j a v  a  2  s.  c om*/
    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:com.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());
    onPrepareRequest(httpRequest);/*from  w ww  .jav a 2 s .co  m*/
    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, 20000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}

From source file:com.socialize.net.DefaultHttpClientFactory.java

@Override
public void init(SocializeConfig config) throws SocializeException {

    try {/*from   w ww . j a va 2  s. c om*/
        if (logger != null && logger.isDebugEnabled()) {
            logger.debug("Initializing " + getClass().getSimpleName());
        }

        params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params,
                config.getIntProperty(SocializeConfig.HTTP_CONNECTION_TIMEOUT, 10000));
        HttpConnectionParams.setSoTimeout(params,
                config.getIntProperty(SocializeConfig.HTTP_SOCKET_TIMEOUT, 10000));

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        connectionManager = new ThreadSafeClientConnManager(params, registry);

        monitor = new IdleConnectionMonitorThread(connectionManager);
        monitor.setDaemon(true);
        monitor.start();

        if (logger != null && logger.isDebugEnabled()) {
            logger.debug("Initialized " + getClass().getSimpleName());
        }

        destroyed = false;
    } catch (Exception e) {
        throw new SocializeException(e);
    }
}

From source file:org.frameworkset.spi.remote.http.Client.java

public static HttpParams buildHttpParams() {

    int so_timeout = conparams.getInt("http.socket.timeout", 30);//??

    int CONNECTION_TIMEOUT = conparams.getInt("http.connection.timeout", 30);
    int CONNECTION_Manager_TIMEOUT = conparams.getInt("http.conn-manager.timeout", 2);
    int httpsoLinger = conparams.getInt("http.soLinger", -1);
    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setSoTimeout(params, so_timeout * 1000);
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT * 1000);
    HttpConnectionParams.setLinger(params, httpsoLinger);
    ConnManagerParams.setTimeout(params, CONNECTION_Manager_TIMEOUT * 1000);
    //      params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, 
    //            "org.frameworkset.spi.remote.http.BBossClientConnectionManagerFactory");
    return params;
}

From source file:jsonbroker.library.client.http.HttpDispatcher.java

public HttpDispatcher(NetworkAddress networkAddress) {

    _networkAddress = networkAddress;//ww  w .j a  v a 2s  .c o m

    /*
      with ... 
      _client = new DefaultHttpClient();
      ... we get the following error ... 
      "Invalid use of SingleClientConnManager: connection still allocated.\nMake sure to release the connection before allocating another one."
      ... using a thread safe connecion manager ... 
      * http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
      * http://thinkandroid.wordpress.com/2009/12/31/creating-an-http-client-example/ 
     */

    //sets up parameters
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    // timeouts ... 
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);

    //registers schemes for both http and https
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    registry.register(new Scheme("https", sslSocketFactory, 443));

    ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
    _client = new DefaultHttpClient(manager, params);

}

From source file:org.transdroid.search.Demonoid.DemonoidAdapter.java

@Override
public List<SearchResult> search(Context context, String query, SortOrder order, int maxResults)
        throws Exception {

    if (query == null) {
        return null;
    }/*from w w w . j  av a  2  s.  c  om*/

    this.maxResults = maxResults;

    // Build a search request parameters
    String encodedQuery = "";
    try {
        encodedQuery = URLEncoder.encode(query, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw e;
    }

    final String url = String.format(QUERYURL, encodedQuery,
            (order == SortOrder.BySeeders ? SORT_SEEDS : SORT_COMPOSITE));

    // Start synchronous search

    // Setup request using GET
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);
    // Spoof Firefox user agent to force a result
    httpclient.getParams().setParameter("http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    HttpGet httpget = new HttpGet(url);

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

    // Read HTML response
    InputStream instream = response.getEntity().getContent();
    String html = HttpHelper.convertStreamToString(instream);
    instream.close();
    return parseHtml(html);

}

From source file:org.transdroid.search.AsiaTorrents.AsiaTorrentsAdapter.java

private DefaultHttpClient prepareRequest(Context context) throws Exception {

    String username = SettingsHelper.getSiteUser(context, TorrentSite.AsiaTorrents);
    String password = SettingsHelper.getSitePass(context, TorrentSite.AsiaTorrents);
    if (username == null || password == null) {
        throw new InvalidParameterException(
                "No username or password was provided, while this is required for this private site.");
    }/*from   w w w.j a  va  2  s .c  o m*/

    // Setup request using GET
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);

    // First log in
    HttpPost loginPost = new HttpPost(LOGINURL);
    loginPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair[] {
            new BasicNameValuePair(LOGIN_USER, username), new BasicNameValuePair(LOGIN_PASS, password) })));
    HttpResponse loginResult = httpclient.execute(loginPost);
    if (loginResult.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        // Failed to sign in
        throw new LoginException("Login failure for AsiaTorrents with user " + username);
    }

    return httpclient;

}

From source file:com.bai.android.data.arcamera.DownloadContent.java

/**
 * The method that carries out the download and saving of the file to the according path 
 *///from   w w  w .j ava 2s  .co  m
public void downloadFile() throws Exception {
    ManageFileService manageFileService = new ManageFileService(localFileLocation);
    if (manageFileService.cardChecks() == true) {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
        HttpConnectionParams.setSoTimeout(httpParameters, 15000);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);

        DefaultHttpClient client = new DefaultHttpClient(httpParameters);

        HttpGet request = new HttpGet(downloadUrl.toString());

        //get path for file save and prepare output stream to write the file;

        FileOutputStream fileOutput = new FileOutputStream(manageFileService.createFileForDownload());

        // Get the response
        HttpResponse response = client.execute(request);

        //start getting the data from the url input stream
        InputStream inputStream = response.getEntity().getContent();

        //create a buffer
        byte[] buffer = new byte[1024];
        int bufferLength = 0; //used to store a temporary size of the buffer

        //read through the input buffer and write the contents to the file
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            //add the data in the buffer to the file in the file output stream
            fileOutput.write(buffer, 0, bufferLength);
        }
        //close the output stream when done
        fileOutput.close();
    } else {
        //TODO toast error
    }
    if (manageFileService.fileExists() == true) {
        String zipFile = localFileLocation;
        Decompress d = new Decompress(zipFile, unzipLocation);
        d.unzip();
        manageFileService.deleteFile();
    } else {
        //TODO toast error
    }
}