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.wareninja.opensource.common.wsrequest.WebServiceNew.java

public WebServiceNew(String serviceName) {
    HttpParams myParams = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(myParams, TIMEOUT);
    HttpConnectionParams.setSoTimeout(myParams, TIMEOUT);
    httpClient = new DefaultHttpClient(myParams);
    localContext = new BasicHttpContext();

    webServiceUrl = serviceName;/*ww w . j  av a2  s  .  c om*/
}

From source file:com.halseyburgund.rwframework.core.RWHttpManager.java

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

    HttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpPost request = new HttpPost(page);
    HttpResponse response = null;//from   ww  w  .  jav  a  2s  .c om
    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);

        Log.e(TAG, "Error status code = " + status, null);
        Log.e(TAG, ostream.toString(), null);
        throw new HttpException(String.valueOf(status));
    } else {
        InputStream content = response.getEntity().getContent();
        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:org.openqa.selenium.remote.internal.HttpClientFactory.java

public HttpParams getHttpParams() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setSoReuseaddr(params, true);
    HttpConnectionParams.setConnectionTimeout(params, 120 * 1000);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_THREE_HOURS);
    params.setIntParameter(ConnConnectionPNames.MAX_STATUS_LINE_GARBAGE, 0);
    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    return params;
}

From source file:ca.sqlpower.enterprise.ServerInfoProvider.java

private static void init(URL url, String username, String password, CookieStore cookieStore)
        throws IOException {

    if (version.containsKey(generateServerKey(url, username, password)))
        return;/*  w  w w.  j a va 2s  . c  o  m*/

    try {
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 2000);
        DefaultHttpClient httpClient = new DefaultHttpClient(params);
        httpClient.setCookieStore(cookieStore);
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        HttpUriRequest request = new HttpOptions(url.toURI());
        String responseBody = httpClient.execute(request, new BasicResponseHandler());

        // Decode the message
        String serverVersion;
        Boolean licensedServer;
        final String watermarkMessage;
        try {
            JSONObject jsonObject = new JSONObject(responseBody);
            serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString());
            licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString());
            watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString());
        } catch (JSONException e) {
            throw new IOException(e.getMessage());
        }

        // Save found values
        version.put(generateServerKey(url, username, password), new Version(serverVersion));
        licenses.put(generateServerKey(url, username, password), licensedServer);
        watermarkMessages.put(generateServerKey(url, username, password), watermarkMessage);

        // Notify the user if the server is not licensed.
        if (!licensedServer || (watermarkMessage != null && watermarkMessage.trim().length() > 0)) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    HyperlinkListener hyperlinkListener = new HyperlinkListener() {
                        @Override
                        public void hyperlinkUpdate(HyperlinkEvent e) {
                            try {
                                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                                    if (e.getURL() != null) {
                                        BrowserUtil.launch(e.getURL().toString());
                                    }
                                }
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    };
                    HTMLUserPrompter htmlPrompter = new HTMLUserPrompter(UserPromptOptions.OK,
                            UserPromptResponse.OK, null, watermarkMessage, hyperlinkListener, "OK");
                    htmlPrompter.promptUser("");
                }
            });
        }

    } catch (URISyntaxException e) {
        throw new IOException(e.getLocalizedMessage());
    }
}

From source file:com.photowall.oauth.util.BaseHttpClient.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 w w .jav a 2s.co  m*/
public static BaseHttpClient newInstance(Context mContext, 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));
    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 BaseHttpClient(mContext, manager, params);
}

From source file:csic.ceab.movelab.beepath.Fix.java

public boolean uploadJSON(Context context) {

    String response = "";

    String uploadurl = Util.URL_FIXES_JSON;

    try {/*from w w w  .j  a  v a  2 s.c om*/

        // Create a new HttpClient and Post Header
        HttpPost httppost = new HttpPost(uploadurl);

        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 60000);
        HttpConnectionParams.setTcpNoDelay(myParams, true);

        httppost.setHeader("Content-type", "application/json");
        HttpClient httpclient = new DefaultHttpClient();

        StringEntity se = new StringEntity(exportJSON(context).toString(), HTTP.UTF_8);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);

        // Execute HTTP Post Request

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        response = httpclient.execute(httppost, responseHandler);

    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }

    if (response.contains("SUCCESS")) {

        return true;
    } else {
        return false;
    }

}

From source file:com.eventcentric.helper.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 ww w. ja  v  a 2 s .  c  o m*/
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));
    //schemeRegistry.register(new Scheme("https",
    //        socketFactoryWithCache(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 AndroidHttpClient(manager, params);
}

From source file:com.amazonaws.services.dynamodbv2.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from w  ww  . j a v a2s.  c  o m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public CloseableHttpAsyncClient 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);
    HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive());

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

    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();

    /* httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton);
     httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy());
            
     if (config.getConnectionMaxIdleMillis() > 0) {
    httpClient.setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(
            config.getConnectionMaxIdleMillis()));
     }*/

    if (config.getLocalAddress() != null) {
        ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress());
    }

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = config.getApacheHttpClientConfig().getSslSocketFactory();
        if (sf == null) {
            sf = new SdkTLSSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        }
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("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));
    }
            
    // Add a request interceptor that sets up proxy authentication pre-emptively if configured
    if (config.isPreemptiveBasicProxyAuth()){
        httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
    }
    }
    */
    /* Accept Gzip response if configured */
    if (config.useGzip()) {
        /*
                    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
                
        @Override
        public void process(final HttpRequest request,
                final HttpContext context) throws HttpException,
                IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
                
                    });
                
                    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
                
        @Override
        public void process(final HttpResponse response,
                final HttpContext context) throws HttpException,
                IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName()
                                .equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(
                                    response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
                
                    });*/
    }

    return httpClient;
}

From source file:org.androdyne.StacktraceUploader.java

/**
 * Initialize HTTP client with common parameters.
 **//*  w ww.j a v  a  2s .c  o  m*/
private void setupHTTPClient() {
    // Create connection manager/client.
    if (null == mConnectionManager || null == mClient) {
        // Set up an HttpClient instance that can be used by multiple threads
        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpProtocolParams.setVersion(params, HTTP_VERSION);

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

        mConnectionManager = new ThreadSafeClientConnManager(params, registry);
        mClient = new DefaultHttpClient(mConnectionManager, params);
    }
}

From source file:com.github.ignition.support.http.IgnitedHttpClient.java

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_READ_STREAM_TIMEOUT);
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (DiagnosticSupport.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {//ww w .  ja  v a2s  .  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);

}