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.betaplay.sdk.http.HttpClient.java

private void executeRequest(HttpUriRequest request, String url) {

    DefaultHttpClient client = sslClient(new DefaultHttpClient());
    HttpParams params = client.getParams();

    // timeout 40 sec
    HttpConnectionParams.setConnectionTimeout(params, 40 * 1000);
    HttpConnectionParams.setSoTimeout(params, 40 * 1000);

    HttpResponse httpResponse;//  w ww  .  j  a v a  2  s .  c  o  m

    try {
        httpResponse = client.execute(request);
        mResponseCode = httpResponse.getStatusLine().getStatusCode();
        mMessage = httpResponse.getStatusLine().getReasonPhrase();

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            mResponse = convertStreamToString(instream);

            instream.close();
        }

    } catch (ClientProtocolException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

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

@Override
public InputStream getTorrentFile(Context context, String url) throws Exception {

    // Provide a simple file handle to the requested url
    HttpParams httpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpparams);
    HttpResponse response = httpclient.execute(new HttpGet(url));
    return response.getEntity().getContent();

}

From source file:com.jute.fed4j.engine.component.http.HttpDispatcherImpl_Jakarta.java

public void run(HttpComponent component) {
    this.commponent = component;
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, component.connectTimeout);
    HttpConnectionParams.setSoTimeout(params, component.readTimeout);

    try {/*from  w w w.ja  va  2s  . c  o m*/
        this.init(component);
        HttpClient httpclient = new MyHttpClient(
                getConnectionManager(params, component.enablePersistentConnection), params);
        if (component.enableProxy && "http".equals(component.proxyType)) {
            HttpHost proxy = new HttpHost(component.proxyHost, component.proxyPort, component.proxyType);
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        HttpUriRequest request = new HttpRequest(component.method, component.uri);
        MyHttpResponseHandler responseHandler = new MyHttpResponseHandler(component.responseCharset);
        String body = httpclient.execute(request, responseHandler);
        this.onResponse(component, responseHandler.code, body);
    } catch (SocketTimeoutException e) {
        onException(component, -2, " socket timeout error occurs: " + e.getMessage());
    } catch (ClientProtocolException e) {
        onException(component, -3, " error resposed from server: " + e.getMessage());
    } catch (IOException e) {
        onException(component, -4, " error occurs during dispatch: " + e.getMessage());
    } catch (Exception e) {
        onException(component, -5, "error occurs during parsing xml:" + e.getMessage());
    }
}

From source file:br.com.anteros.android.synchronism.communication.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * //w w w . j  av a  2  s  . c  o m
 * @param userAgent
 *            to report in your HTTP requests.
 * @param sessionCache
 *            persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static AndroidHttpClient newInstance(String userAgent) {
    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, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // 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);

    // 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));

    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.betfair.cougar.client.HttpClientExecutable.java

public void init() throws Exception {
    super.init();

    // create client if not been set externally (e.g for testing)
    if (client == null) {
        client = new DefaultHttpClient(clientConnectionManager);
        ((DefaultHttpClient) client).setUserTokenHandler(userTokenHandler);
    }// www .  j  a v  a  2s  .c  om

    // configure retryhandler if set
    if (retryHandler != null) {
        ((AbstractHttpClient) client).setHttpRequestRetryHandler(retryHandler);
    }

    // configure timeout if set
    if (connectTimeout != -1) {
        HttpParams params = client.getParams();
        HttpConnectionParams.setConnectionTimeout(params, connectTimeout);
        HttpConnectionParams.setSoTimeout(params, connectTimeout);
    }

    //Configure SSL - if relevant
    if (transportSSLEnabled) {
        KeyStoreManagement keyStore = KeyStoreManagement.getKeyStoreManagement(httpsKeystoreType, httpsKeystore,
                httpsKeyPassword);
        if (jmxControl != null && keyStore != null) {
            jmxControl.registerMBean("CoUGAR:name=HttpClientKeyStore,beanName=" + beanName, keyStore);
        }
        KeyStoreManagement trustStore = KeyStoreManagement.getKeyStoreManagement(httpsTruststoreType,
                httpsTruststore, httpsTrustPassword);
        if (jmxControl != null) {
            jmxControl.registerMBean("CoUGAR:name=HttpClientTrustStore,beanName=" + beanName, trustStore);
        }
        SSLSocketFactory socketFactory = new SSLSocketFactory(keyStore != null ? keyStore.getKeyStore() : null,
                keyStore != null ? httpsKeyPassword : null, trustStore.getKeyStore());
        if (hostnameVerificationDisabled) {
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            LOGGER.warn("CRITICAL SECURITY CHECKS ARE DISABLED: server SSL certificate hostname "
                    + "verification is turned off.");
        }
        Scheme sch = new Scheme("https", extractPortFromAddress(), socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    }

    metrics = new HttpClientTransportMetrics();

    if (jmxControl != null) {
        jmxControl.registerMBean("CoUGAR:name=HttpClientExecutable,beanName=" + beanName, this);
    }
}

From source file:me.pjq.benchmark.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests.
 * @param sessionCache persistent session cache
 * @return AndroidHttpClient for you to use for all your requests.
 *///from w  ww.  j av a2s  .c o m

public static AndroidHttpClient newInstance(String userAgent)/*,
                                                             SSLClientSessionCache sessionCache) 
                                                             */
{
    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, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // 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);

    // 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));
    //        schemeRegistry.register(new Scheme("https",
    //                socketFactoryWithCache(sessionCache), 443));

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    //        DhcpInfo info = new DhcpInfo();
    //        UVANLogger.getInstance().d("Server", info.toString());

    //to do waiting for a while
    //        HttpHost host = UVANApplication.getHttpProxy();
    //        if (host==null){
    //           host = new HttpHost("0.0.0.0");
    //        }
    //        HttpRoute route = new HttpRoute(host);
    //        
    //        Object object = new Object();
    //        try {
    //           ManagedClientConnection managedClientConnection = manager.requestConnection(route, object).getConnection(20 * 1000, TimeUnit.MILLISECONDS);
    //           managedClientConnection.setIdleDuration(5 * 60 * 1000, TimeUnit.MILLISECONDS);
    //        } catch (ConnectionPoolTimeoutException e) {
    //         e.printStackTrace();
    //      } catch (InterruptedException e) {
    //         e.printStackTrace();
    //      }

    // 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.taqueue.connection.QueueConnectionManager.java

/**
 * Sends a POST to the queue with the parameters nvps, returns the result.
 * @param nvps the NameValuePair of parameters to be sent to the queue server
 * @return ConnectionResult containing the status code for the attempt and the message returned
 * message will be null iff the status is not OK
 *//*  ww w .j a  va 2  s. c  o m*/
private ConnectionResult sendMessage(List<NameValuePair> nvps) {
    ConnectionResult res = new ConnectionResult();
    //default to OK, we'll change in the event of an error
    res.status = ConnectionStatus.OK;
    HttpPost post = new HttpPost(HOST + PATH);
    //DefaultHttpClient client = new DefaultHttpClient();
    //set up the timeout
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);
    // set up the connection manager if needed
    if (manager == null) {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        manager = new ThreadSafeClientConnManager(httpParams, registry);
    }
    DefaultHttpClient client = new DefaultHttpClient(manager, httpParams);
    try {
        //set up our POST values
        post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        //send it along
        ResponseHandler<String> handler = new BasicResponseHandler();
        connectionWatcher watcher = new connectionWatcher(post);
        Thread t = new Thread(watcher);
        t.start();
        res.message = client.execute(post, handler);
        watcher.finished();
        //and clean up
        //if any exceptions are thrown return a connection error result
    } catch (Exception e) {
        res.status = ConnectionStatus.CONNECTION_ERROR;
        res.message = null;
    } finally {
        post.abort();
    }
    return res;
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPutCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;/* w  w w.java2 s  .  c o  m*/
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPut putRequest = new HttpPut(url);
        putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        putRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(putRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute PUT URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}