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:cn.com.zzwfang.http.HttpClient.java

/**
 * Cookie/* ww w.j a v a  2  s . c  om*/
 */
//   private PersistentCookieStore cookieStore;

public HttpClient(Context context) {
    if (httpClient != null) {
        return;
    }
    //      Log.i("--->", "HttpClient ?httpClient-------------");
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, totalConnections);

    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, userAgent);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.setHttpRequestRetryHandler(new InnerRetryHandler(DEFAULT_MAX_RETRIES));
    //      cookieStore = new PersistentCookieStore(context);
    //      httpContext.setAttribute("http.cookie-store", cookieStore);
    //      httpClient.setCookieStore(cookieStore);

}

From source file:com.louding.frame.http.download.SimpleDownloader.java

/**
 * ?httpClient//  w  ww .j a va  2  s.  c  o  m
 */
private void initHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, config.timeOut);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(config.maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, config.maxConnections);

    HttpConnectionParams.setSoTimeout(httpParams, config.timeOut);
    HttpConnectionParams.setConnectionTimeout(httpParams, config.timeOut);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, config.socketBuffer);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "KJLibrary");

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    context = new SyncBasicHttpContext(new BasicHttpContext());
    client = new DefaultHttpClient(cm, httpParams);
    client.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }

            for (Entry<String, String> entry : config.httpHeader.entrySet()) {
                request.addHeader(entry.getKey(), entry.getValue());
            }
        }
    });

    client.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });
    client.setHttpRequestRetryHandler(new RetryHandler(config.timeOut));
}

From source file:com.aol.webservice_base.util.http.HttpHelper.java

/**
 * Inits the.//from  w  w  w.j  a  v  a  2  s .c o m
 */
public void init() {
    inited = true;
    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager();
    connectionManager.setDefaultMaxPerRoute(maxConnectionsPerHost);
    connectionManager.setMaxTotal(maxTotalConnections);

    httpClient = new DefaultHttpClient(connectionManager);
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);
}

From source file:com.cloudbees.eclipse.core.ClickStartService.java

/**
 * @param templateId/*from   w w  w  . jav a 2s.co  m*/
 * @param account
 * @param name
 * @return
 * @throws CloudBeesException
 */
public ClickStartCreateResponse create(String template, String account, String name) throws CloudBeesException {
    //* curl -i -X POST
    //"http://localhost:8080/api/apps/json/launch?account=michaelnealeclickstart2&name=nodecli&template=https://raw.github.com/CloudBees-community/nodejs-clickstart/master/clickstart.json"
    StringBuffer errMsg = new StringBuffer();

    try {
        String url = CS_API_URL + "launch?account=" + account + "&name=" + name + "&template=" + template;
        HttpClient httpclient = Utils.getAPIClient(url);

        HttpParams params = httpclient.getParams();
        // Override timeouts, this request can be long..
        HttpConnectionParams.setConnectionTimeout(params, 6 * 60 * 1000);
        HttpConnectionParams.setSoTimeout(params, 6 * 60 * 1000);

        HttpPost get = Utils.jsonRequest(url, "");
        applyAuth(get);
        System.out.println("Request URL: " + url);
        System.out.println(
                "curl --header \"Authorization: Basic NzgxNUI0MUQzRjREOTk2ODpVUDQzM1NURjFOQjlZRElFRytWSzk4RFhNQjBDSExPRko2WFlFQlRIMENBPQ==\" -i -X POST \""
                        + url + "\"");
        HttpResponse resp = httpclient.execute(get);
        String bodyResponse = Utils.getResponseBody(resp);
        System.out.println("JSON RESPONSE for the create command:\n" + bodyResponse);
        Gson g = Utils.createGson();
        ClickStartCreateResponse r = g.fromJson(bodyResponse, ClickStartCreateResponse.class);

        checkForErrors(resp, r);

        return r;

    } catch (Exception e) {
        throw new CloudBeesException("Failed to create from template " + template + " for account " + account
                + " using name " + name + (errMsg.length() > 0 ? " (" + errMsg + ")" : ""), e);
    }

}

From source file:com.ushahidi.android.app.net.MainHttpClient.java

public MainHttpClient() {

    httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    httpClient = new DefaultHttpClient(httpParameters);
}

From source file:com.novoda.commons.net.httpclient.NovodaHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*from   w  w w. ja  v a  2s .c  o m*/
 * @param userAgent
 *            to report in your HTTP requests.
 * @return AndroidHttpClient for you to use for all your requests.
 */
public static NovodaHttpClient 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);

    HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT);
    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 NovodaHttpClient(manager, params);
}

From source file:ru.neverdark.phototools.azimuth.model.Geocoder.java

/**
 * Gets json for location//  www  . j a  v  a  2  s.  c o m
 *
 * @param searchString location for search
 * @return json for location or empty string if connection problem
 */
private String getLocationInfo(String searchString) {
    String query = null;
    try {
        query = URLEncoder.encode(searchString, "UTF-8");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    String url = String.format("http://maps.google.com/maps/api/geocode/json?address=%s&sensor=false", query);
    StringBuilder builder = new StringBuilder();

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 4000); // 4 sec
    HttpConnectionParams.setSoTimeout(params, 1000); // 1 sec

    HttpClient client = new DefaultHttpClient(params);
    HttpGet httpGet = new HttpGet(url);
    httpGet.setParams(params);

    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.message("Download fail");
        }
    } catch (Exception e) {
        // request new address for object
        // creating new object is a faster then setLength(0)
        builder = new StringBuilder();
    }

    return builder.toString();
}

From source file:com.marketplace.io.Sender.java

/**
 * Constructs a <code>Sender</code>
 *//*from   ww w  .jav a 2s  .  com*/
public Sender() {
    this.httpPut = new HttpPut();
    this.httpPost = new HttpPost();

    this.httpClient = new DefaultHttpClient();
    this.httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpConnectionParams.setConnectionTimeout(this.httpClient.getParams(), 20000);

}