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:ca.sqlpower.enterprise.ClientSideSessionUtils.java

public static HttpClient createHttpClient(SPServerInfo serviceInfo, CookieStore cookieStore) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 2000);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.setCookieStore(cookieStore);
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(serviceInfo.getServerAddress(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(serviceInfo.getUsername(), serviceInfo.getPassword()));
    return httpClient;
}

From source file:at.alladin.rmbt.client.helper.JSONParser.java

public JSONObject getURL(final URI uri) {
    JSONObject jObj = null;//from   w  w w  .  java  2s . c o  m
    String responseBody;

    try {
        final HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 20000);
        HttpConnectionParams.setSoTimeout(params, 20000);
        final HttpClient client = new DefaultHttpClient(params);

        final HttpGet httpget = new HttpGet(uri);

        final ResponseHandler<String> responseHandler = new BasicResponseHandler();
        responseBody = client.execute(httpget, responseHandler);

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(responseBody);
        } catch (final JSONException e) {
            writeErrorList("Error parsing JSON " + e.toString());
        }

    } catch (final UnsupportedEncodingException e) {
        writeErrorList("Wrong encoding");
        // e.printStackTrace();
    } catch (final HttpResponseException e) {
        writeErrorList(
                "Server responded with Code " + e.getStatusCode() + " and message '" + e.getMessage() + "'");
    } catch (final ClientProtocolException e) {
        writeErrorList("Wrong Protocol");
        // e.printStackTrace();
    } catch (final IOException e) {
        writeErrorList("IO Exception");
        e.printStackTrace();
    }

    // return JSONObject
    return jObj;
}

From source file:net.sarangnamu.common.network.BkHttp.java

public void setTimeout(int connTimeout, int socketTimeout) {
    if (http == null) {
        return;/*from www.  j a  va2s .co  m*/
    }

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, connTimeout);
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    http.setParams(httpParameters);
}

From source file:com.base.httpclient.HttpJsonClient.java

/**
 * httpClient//from w w w.  j  av  a  2  s.co  m
 * @return
 */
public static DefaultHttpClient getHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    HttpParams httpParams = new BasicHttpParams();
    cm.setMaxTotal(10);//   
    cm.setDefaultMaxPerRoute(5);// ? 
    HttpConnectionParams.setConnectionTimeout(httpParams, 60000);//
    HttpConnectionParams.setSoTimeout(httpParams, 60000);//?
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(httpParams, false);
    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    DefaultHttpClient httpClient = new DefaultHttpClient(cm, httpParams);
    //httpClient.setCookieStore(null);
    httpClient.getCookieStore().clear();
    httpClient.getCookieStore().getCookies().clear();
    //   httpClient.setHttpRequestRetryHandler(new HttpJsonClient().new HttpRequestRetry());//?
    return httpClient;
}

From source file:com.core.ServerConnector.java

public static String GET(String endpoint, Map<String, String> params, Map<String, String> header)
        throws Exception {
    String result = null;//from  w w  w .j  a  v a 2  s .c  om
    StringBuilder bodyBuilder = new StringBuilder(endpoint).append("?");
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    //Log.i("SCANTRANX", "URL:"+body);
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);
    HttpClient client = new DefaultHttpClient(httpParameters);
    HttpGet request = new HttpGet(body);

    for (Entry<String, String> mm : header.entrySet()) {
        request.addHeader(mm.getKey(), mm.getValue());
    }
    System.out.println("Raw Request:" + request);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        result = SystemUtil.convertStreamToString(instream);
        instream.close();
    }

    return result;
}

From source file:net.peterkuterna.android.apps.devoxxsched.util.SyncUtils.java

/**
 * Generate and return a {@link HttpClient} configured for general use,
 * including setting an application-specific user-agent string.
 *///  ww  w  .  ja v a2s . c o  m
public static HttpClient getHttpClient(Context context) {
    final HttpParams params = new BasicHttpParams();

    // Use generous timeouts for slow mobile networks
    HttpConnectionParams.setConnectionTimeout(params, 200 * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, 200 * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

    final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    sslSocketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    final SchemeRegistry schemeReg = new SchemeRegistry();
    schemeReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeReg.register(new Scheme("https", sslSocketFactory, 443));
    final ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeReg);
    final DefaultHttpClient client = new DefaultHttpClient(connectionManager, params);

    client.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            // Add header to accept gzip content
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            // Inflate any responses compressed with gzip
            final HttpEntity entity = response.getEntity();
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    return client;
}

From source file:de.jetwick.snacktory.HijackableHttpPageReader.java

/** {@inheritDoc}*/
@SuppressWarnings("deprecation")
@Override/*from  ww w.jav a2  s.  c o  m*/
public String readPage(String url) throws PageReadException {
    if (url.equals(this.url) && StringUtils.isNotEmpty(pageHtml)) {
        LOG.info("Use already fetched content of " + url);

        return pageHtml;
    } else {
        LOG.info("Reading " + url);
        this.url = url;
        this.pageHtml = null;

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

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpContext localContext = new BasicHttpContext();
        HttpGet get = new HttpGet(url);
        get.setHeader("User-Agent", userAgent);
        InputStream response = null;
        HttpResponse httpResponse = null;
        try {
            try {
                httpResponse = httpclient.execute(get, localContext);
                int resp = httpResponse.getStatusLine().getStatusCode();
                if (HttpStatus.SC_OK != resp) {
                    LOG.error("Download failed of " + url + " status " + resp + " "
                            + httpResponse.getStatusLine().getReasonPhrase());
                    return null;
                }
                String respCharset = EntityUtils.getContentCharSet(httpResponse.getEntity());

                pageHtml = readContent(httpResponse.getEntity().getContent(), respCharset);
                return pageHtml;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (httpResponse != null && httpResponse.getEntity() != null) {
                    httpResponse.getEntity().consumeContent();
                }

            }
        } catch (IOException e) {
            LOG.error("Download failed of " + url, e);
            throw new PageReadException("Failed to read " + url, e);
        }
    }
}

From source file:ch.ethz.dcg.pancho3.view.youtube.Query.java

private void initializeHttpClient() {
    // Initialize Http client
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
    httpClient = new DefaultHttpClient(params);

    HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(2, true);
    httpClient.setHttpRequestRetryHandler(retryHandler);
}

From source file:com.android.dumprendertree2.FsUtils.java

private static HttpClient getHttpClient() {
    if (sHttpClient == null) {
        HttpParams params = new BasicHttpParams();

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(//from www.  ja va 2s  . c  o  m
                new Scheme("http", PlainSocketFactory.getSocketFactory(), ForwarderManager.HTTP_PORT));
        schemeRegistry.register(
                new Scheme("https", SSLSocketFactory.getSocketFactory(), ForwarderManager.HTTPS_PORT));

        ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
        sHttpClient = new DefaultHttpClient(connectionManager, params);
        HttpConnectionParams.setSoTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
        HttpConnectionParams.setConnectionTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
    }
    return sHttpClient;
}

From source file:com.qingzhi.apps.fax.client.NetworkUtilities.java

private static String executeGet(String url, Map<String, String> map) throws IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_SO_TIMEOUT);

    HttpPost post = new HttpPost(url);

    ArrayList<BasicNameValuePair> postDate = new ArrayList<BasicNameValuePair>();
    Set<String> set = map.keySet();
    Iterator<String> iterator = set.iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        postDate.add(new BasicNameValuePair(key, map.get(key)));
    }/*from w  w  w  .  j a va 2 s .  com*/
    post.setEntity(new UrlEncodedFormEntity(postDate, HTTP.UTF_8));
    HttpResponse httpResponse = httpclient.execute(post);
    throwErrors(httpResponse);

    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        String response = EntityUtils.toString(httpEntity);
        LOGD(TAG, response);
        return response;
    }
    return null;
}