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

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

Introduction

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

Prototype

public static void setSoTimeout(HttpParams httpParams, int i) 

Source Link

Usage

From source file:read.taz.TazDownloader.java

private void downloadFile() throws ClientProtocolException, IOException {
    if (tazFile.file.exists()) {
        Log.w(getClass().getSimpleName(), "File " + tazFile + " exists.");
        return;/*from   w w  w . j a  v a2  s . c  o m*/
    }
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 15000);

    DefaultHttpClient client = new DefaultHttpClient(httpParams);

    Credentials defaultcreds = new UsernamePasswordCredentials(uname, passwd);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(/* FIXME DRY */"dl.taz.de", 80, AuthScope.ANY_REALM), defaultcreds);

    URI uri = tazFile.getDownloadURI();
    Log.d(getClass().getSimpleName(), "Downloading taz from " + uri);
    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Download failed with HTTP Error" + response.getStatusLine().getStatusCode());
    }

    String contentType = response.getEntity().getContentType().getValue();
    if (contentType.startsWith("text/html")) {
        Log.d(getClass().getSimpleName(),
                "Content type: " + contentType + " encountered. Assuming a non exisiting file");

        ByteArrayOutputStream htmlOut = new ByteArrayOutputStream();
        response.getEntity().writeTo(htmlOut);
        String resp = new String(htmlOut.toByteArray());
        Log.d(getClass().getSimpleName(), "Response: " + resp);
        throw new FileNotFoundException("No taz found for date " + tazFile.date.getTime());
    } else {
        FileOutputStream tazOut = new FileOutputStream(tazFile.file);
        try {
            response.getEntity().writeTo(tazOut);
        } finally {
            tazOut.close();
        }
    }

    // InputStream docStream = response.getEntity().getContent();
    // FileOutputStream out = null;
    // try {
    // out = tazOut;
    // byte[] buf = new byte[4096];
    // for (int read = docStream.read(buf); read != -1; read = docStream
    // .read(buf)) {
    // out.write(buf, 0, read);
    // }
    // } finally {
    // docStream.close();
    // if (out != null) {
    // out.close();
    // }
    // }

}

From source file:com.DGSD.DGUtils.Http.BetterHttp.java

public static void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, httpUserAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticUtils.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {/*w w w  . jav  a 2s .c o  m*/
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}

From source file:cn.clxy.codes.upload.ApacheHCUploader.java

/**
 * The timeout should be adjusted by network condition.
 * @return/* w  w w.  j av  a 2 s .  c  o m*/
 */
private static HttpClient createClient() {

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

    PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schReg);
    ccm.setMaxTotal(Config.MAX_UPLOAD);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
    HttpConnectionParams.setSoTimeout(params, Config.PART_UPLOAD_TIMEOUT);

    return new DefaultHttpClient(ccm, params);
}

From source file:com.photon.phresco.Screens.HttpRequest.java

/**
 * Send the JSON data to specified URL and get the httpResponse back
 *
 * @param sURL//  ww  w.  ja va2  s  . co m
 * @param jObject
 * @return InputStream
 * @throws IOException
 */
public static InputStream post(String sURL, JSONObject jObject) throws IOException {
    HttpResponse httpResponse = null;
    InputStream is = null;

    HttpPost httpPostRequest = new HttpPost(sURL);
    HttpEntity entity;

    httpPostRequest.setHeader("Accept", "application/json");
    httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");
    httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8")));
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpResponse = httpClient.execute(httpPostRequest);

    if (httpResponse != null) {
        entity = httpResponse.getEntity();
        is = entity.getContent();
    }
    return is;
}

From source file:eu.trentorise.smartcampus.portfolio.utils.HttpClientFactory.java

private final HttpClient createHttpClient() {
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, HTTP.DEFAULT_CONTENT_CHARSET);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme httpScheme = new Scheme(HTTP_SCHEMA, PlainSocketFactory.getSocketFactory(), 80);
    schemeRegistry.register(httpScheme);
    Scheme httpsScheme = new Scheme(HTTPS_SCHEMA, SSLSocketFactory.getSocketFactory(), 443);
    schemeRegistry.register(httpsScheme);
    ClientConnectionManager tsConnManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    HttpClient client = new DefaultHttpClient(tsConnManager, httpParams);
    HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
    return client;
}

From source file:com.adamrosenfield.wordswithcrosses.versions.DefaultUtil.java

public DefaultUtil() {
    // Set default connect and recv timeouts to 30 seconds
    mHttpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(mHttpParams, 30000);
    HttpConnectionParams.setSoTimeout(mHttpParams, 30000);

    mHttpClient = new DefaultHttpClient(mHttpParams);
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public void setup(Hoot hoot) {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 10);
    ConnManagerParams.setTimeout(params, hoot.getTimeout());
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setConnectionTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setSoTimeout(params, hoot.getTimeout());
    HttpConnectionParams.setTcpNoDelay(params, true);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier(hoot.getSSLHostNameVerifier());
    schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    mClient = new DefaultHttpClient(cm, params);
    if (hoot.isBasicAuth()) {
        mClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(hoot.getBasicAuthUsername(), hoot.getBasicAuthPassword()));
    }//from www  .  ja v  a2s  .c  o m
}

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

/**
 * Create new HTTP client with default configuration and custom trust manager.
 *
 * @return A new instance of a default HTTP client.
 *//*from   w  w  w.  j  av a  2  s.co m*/
protected AbstractHttpClient http() {
    if (null == http) {
        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, "ISO-8859-1");

        HttpConnectionParams.setTcpNoDelay(params, true);
        HttpConnectionParams.setSoTimeout(params, timeout());
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        HttpClientParams.setRedirecting(params, true);
        HttpClientParams.setAuthenticating(params, true);

        SchemeRegistry registry = new SchemeRegistry();
        // Always register HTTP for possible use with proxy
        registry.register(new Scheme("http", host.getPort(), PlainSocketFactory.getSocketFactory()));
        if ("https".equals(this.getHost().getProtocol().getScheme())) {
            org.apache.http.conn.ssl.SSLSocketFactory factory = new SSLSocketFactory(
                    new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(),
                    org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            registry.register(new Scheme(host.getProtocol().getScheme(), host.getPort(), factory));
        }
        if (Preferences.instance().getBoolean("connection.proxy.enable")) {
            final Proxy proxy = ProxyFactory.instance();
            if ("https".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPSProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host)));
                }
            }
            if ("http".equals(this.getHost().getProtocol().getScheme())) {
                if (proxy.isHTTPProxyEnabled(host)) {
                    ConnRouteParams.setDefaultProxy(params,
                            new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host)));
                }
            }
        }
        ClientConnectionManager manager = new SingleClientConnManager(registry);
        http = new DefaultHttpClient(manager, params);
        this.configure(http);
    }
    return http;
}

From source file:com.mykola.lexinproject.providers.LexinTranslator.java

public LexinTranslator(TranslationManagerCallback cb) {
    super(cb);/*from w ww.  j  a va2  s .  c o  m*/
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
    HttpConnectionParams.setSoTimeout(params, 40 * 1000);
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    mHttpClient = new DefaultHttpClient(cm, params);
}

From source file:org.transdroid.search.Fenopy.FenopyAdapter.java

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

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

    // Build search URL
    String url = String.format(RPC_QUERYURL, URLEncoder.encode(query, "UTF-8"),
            order == SortOrder.BySeeders ? RPC_SORT_SEEDS : RPC_SORT_COMPOSITE, String.valueOf(maxResults));

    // Setup HTTP client
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);

    // Make request
    HttpResponse response = httpclient.execute(new HttpGet(url));

    // Read JSON response
    InputStream instream = response.getEntity().getContent();
    JSONArray json = new JSONArray(HttpHelper.ConvertStreamToString(instream));
    instream.close();

    // Add search results
    List<SearchResult> results = new ArrayList<SearchResult>();
    for (int i = 0; i < json.length(); i++) {
        JSONObject item = json.getJSONObject(i);
        results.add(new SearchResult(item.getString("name"), item.getString("torrent"), item.getString("page"),
                FileSizeConverter.getSize(item.getLong("size")), null, item.getInt("seeder"),
                item.getInt("leecher")));
    }

    // Return the results list
    return results;

}