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:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(/*from   ww  w .  j  a  v a2  s. c  om*/
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:com.android.im.imps.HttpDataChannel.java

/**
 * Constructs a new HttpDataChannel for a connection.
 *
 * @param connection the connection which uses the data channel.
 *//* w  w w.  j  a  va  2  s .  com*/
public HttpDataChannel(ImpsConnection connection) throws ImException {
    super(connection);
    mTxManager = connection.getTransactionManager();
    ImpsConnectionConfig cfg = connection.getConfig();
    try {
        String host = cfg.getHost();
        if (host == null || host.length() == 0) {
            throw new ImException(ImErrorInfo.INVALID_HOST_NAME, "Empty host name.");
        }
        mPostUri = new URI(cfg.getHost());
        if (mPostUri.getPath() == null || "".equals(mPostUri.getPath())) {
            mPostUri = new URI(cfg.getHost() + "/");
        }
        if (!"http".equalsIgnoreCase(mPostUri.getScheme()) && !"https".equalsIgnoreCase(mPostUri.getScheme())) {
            throw new ImException(ImErrorInfo.INVALID_HOST_NAME, "Non HTTP/HTTPS host name.");
        }

        mHttpClient = AndroidHttpClient.newInstance("Android-Imps/0.1");

        HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, cfg.getReplyTimeout());
        HttpConnectionParams.setSoTimeout(params, cfg.getReplyTimeout());
    } catch (URISyntaxException e) {
        throw new ImException(ImErrorInfo.INVALID_HOST_NAME, e.getLocalizedMessage());
    }

    mContentTypeHeader = new BasicHeader("Content-Type", cfg.getTransportContentType());
    String msisdn = cfg.getMsisdn();
    mMsisdnHeader = (msisdn != null) ? new BasicHeader("MSISDN", msisdn) : null;

    mParser = cfg.createPrimitiveParser();
    mSerializer = cfg.createPrimitiveSerializer();
}

From source file:com.v2soft.misto.Providers.MapnikProvider.java

@Override
public synchronized boolean prepareTileImage(TileInfo info) {
    try {//from   w  w  w . java  2 s . com
        String local_name = String.format("%d_%d_%d.png", info.getZoom(), info.getLongitude(),
                info.getLatitude());
        if (!mLocalCache.isFileInCache(local_name)) {
            String query = String.format("http://%s/%d/%d/%d%s", BASE_HOST, info.getZoom(), info.getLongitude(),
                    info.getLatitude(), IMAGE_EXT);
            Log.d("Uploading tile ", query);

            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient client = new DefaultHttpClient(httpParameters);

            HttpGet request = new HttpGet(query);

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MONTH, 1);
                RandomAccessFile out = mLocalCache.addFile(local_name, cal.getTime());
                InputStream in = entity.getContent();
                byte[] buffer = new byte[4096];
                int readed = 0;
                while ((readed = in.read(buffer)) > 0) {
                    out.write(buffer, 0, readed);
                }
                out.close();
                in.close();
            }
        }
        InputStream in = mLocalCache.getFileInputStream(local_name);
        final Bitmap bitmap = BitmapFactory.decodeStream(in);
        BitmapManager.registerBitmap(bitmap, info.toString());
        info.setBitmap(bitmap);
        in.close();
        return true;
    } catch (Exception e) {
        Log.d("MapnikProvider::prepareTileImage", e.toString());
    }
    return false;
}

From source file:org.exoplatform.utils.image.SocialImageLoader.java

private Bitmap getBitmap(String url) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try {//from  www.ja v a 2 s. c o m
        File f = fileCache.getFile(url);

        // from SD cache
        Bitmap b = decodeFile(f);
        if (b != null)
            return b;
        else {
            // from web
            Bitmap bitmap = null;
            /*
             * Send authentication each time we execute HttpGet to avoid the step
             * checking session time out.
             */
            HttpGet getRequest = new HttpGet(url);
            StringBuilder buffer = new StringBuilder(username);
            buffer.append(":");
            buffer.append(password);
            getRequest.setHeader("Authorization", "Basic " + Base64.encodeBytes(buffer.toString().getBytes()));
            HttpResponse response = httpClient.execute(getRequest);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = entity.getContent();
                OutputStream os = new FileOutputStream(f);
                PhotoUtils.copyStream(is, os);
                os.close();
                bitmap = decodeFile(f);
            }

            return bitmap;
        }
    } catch (IOException ex) {
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.mongolduu.android.ng.misc.HttpConnector.java

private static HttpClient createHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectHandler(new RedirectHandler());
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    return httpClient;
}

From source file:com.nostra13.example.universalimageloader.ImageGridActivity.java

private void getImageJson() {
    try {//from   www  .j a  v a2s  . c om
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, 0);
        HttpClient httpClient = new DefaultHttpClient(params);

        HttpGet httpget = new HttpGet(imageUrlString);
        HttpEntity entity = httpClient.execute(httpget).getEntity();
        if (entity != null) {
            String response = EntityUtils.toString(entity);
            Log.d("Parse", response);
            entity.consumeContent();
            httpClient.getConnectionManager().shutdown();

            JSONArray json_photoArray = new JSONArray(response);

            if (json_photoArray != null) {
                for (int i = 0; i < json_photoArray.length(); i++) {

                    JSONObject object1 = (JSONObject) json_photoArray.get(i);
                    String photourlString = object1.getString("url");
                    tmp_ImageJsonArray.add(photourlString);
                    Log.d("Photo", photourlString);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        String error = e.toString();
        Log.d("wqe", error);
    }
}

From source file:com.appassit.http.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*w  w  w  .jav a 2 s  .  c o  m*/
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20000);
    HttpConnectionParams.setSoTimeout(params, 20000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Increase max total connection to 60
    ConnManagerParams.setMaxTotalConnections(params, 60);
    // Increase default max connection per route to 20
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20);
    // Increase max connections for localhost:80 to 20
    HttpHost localhost = new HttpHost("locahost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), 20);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);
    // SSLCertificateSocketFactory.getDefault (30 * 1000);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:com.android.callstat.common.net.MyHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * //from  w ww.  j a  v  a 2  s .co  m
 * @param userAgent
 *            to report in your HTTP requests
 * @param context
 *            to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static MyHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();
    HttpLog.v("AndroidHttpClient newInstance#########1111");
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    // Default connection and socket timeout of 20 seconds. Tweak to taste.
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 2048);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, true);
    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new
    // SSLSessionCache(context);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // schemeRegistry.register(new Scheme("https", new
    // DummySSLSocketFactory(),443));
    // schemeRegistry.register(new Scheme("https",
    // SSLCertificateSocketFactory.getHttpSocketFactory(30 * 1000,
    // sessionCache), 443));
    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new MyHttpClient(manager, params);
}

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

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    addHeaders(httpRequest, additionalHeaders);
    onPrepareRequest(httpRequest);//from  w ww  .j a v a2s. 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.sfalma.trace.Sfalma.java

public static void submitError(int sTimeout, Date occuredAt, final String stacktrace) throws Exception {
    // Transmit stack trace with POST request
    try {//  ww w  .  j a va2s  . co  m
        Log.d(G.TAG, "Transmitting stack trace: " + stacktrace);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpParams params = httpClient.getParams();

        // Lighty 1.4 has trouble with the expect header
        // (http://redmine.lighttpd.net/issues/1017), and a
        // potential workaround is only included in 1.4.21
        // (http://www.lighttpd.net/2009/2/16/1-4-21-yes-we-can-do-another-release).
        HttpProtocolParams.setUseExpectContinue(params, false);
        if (sTimeout != 0) {
            HttpConnectionParams.setConnectionTimeout(params, sTimeout);
            HttpConnectionParams.setSoTimeout(params, sTimeout);
        }

        HttpPost httpPost = new HttpPost(G.URL);
        httpPost.addHeader("X-Sfalma-Api-Key", G.API_KEY);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("data",
                createJSON(G.APP_PACKAGE, G.APP_VERSION, G.PHONE_MODEL, G.ANDROID_VERSION, stacktrace,
                        SfalmaHandler.isWifiOn(), SfalmaHandler.isMobileNetworkOn(), SfalmaHandler.isGPSOn(),
                        occuredAt)));
        nvps.add(new BasicNameValuePair("hash", MD5(stacktrace)));

        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        // we don't care about the actual response
        // only if we managed to reach the server

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        // maybe no internet? 
        // save to send another day
        if (entity == null) {
            throw new Exception("no internet connection maybe");
        }

    } catch (Exception e) {
        Log.e(G.TAG, "Error sending exception stacktrace", e);
        throw e;
    }
}