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

/**
 * Cookie/*  w  w  w .j  a va 2  s.  c  o  m*/
 */
//   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.aretha.net.HttpConnectionHelper.java

private HttpConnectionHelper() {
    HttpParams params = mParams = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTION_NUMBER);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    /**//  w  w  w . j  av a  2  s.c  o m
     * android SDK not support MultiThreadedHttpConnectionManager
     * temporarily, so use the {@link ThreadSafeClientConnManager} instead
     */
    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(params,
            schemeRegistry);

    HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS);

    HttpConnectionParams.setSocketBufferSize(params, 8192);

    mHttpClient = new DefaultHttpClient(threadSafeClientConnManager, params);

    mHttpClient.addRequestInterceptor(this);
    mHttpClient.addResponseInterceptor(this);

    mCookieStore = mHttpClient.getCookieStore();
}

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

/**
 * Inits the./*from w w  w .  java 2s.  c  om*/
 */
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   ww w  .  java  2 s.  c  om
 * @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:ru.neverdark.phototools.azimuth.model.Geocoder.java

/**
 * Gets json for location/*from   w  w w . j  a v a 2s .  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.novoda.commons.net.httpclient.NovodaHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /*from   w w w  . j  a  v a 2 s .c om*/
 * @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:com.hotstar.player.adplayer.utils.http.AsyncHttpConnection.java

public void run() {
    _handler.sendMessage(Message.obtain(_handler, AsyncHttpConnection.DID_START));

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

    _httpClient = new DefaultHttpClient(httpParameters);
    try {/*from   ww w  .  j  av  a 2s .  c  o  m*/
        HttpResponse response = null;
        switch (_method) {
        case GET:
            HttpGet httpGet = new HttpGet(_url);
            for (Map.Entry<String, String> header : _headers.entrySet()) {
                httpGet.setHeader(header.getKey(), header.getValue());
            }
            response = _httpClient.execute(httpGet);
            break;
        case POST:
            HttpPost httpPost = new HttpPost(_url);
            for (Map.Entry<String, String> header : _headers.entrySet()) {
                httpPost.setHeader(header.getKey(), header.getValue());
            }
            httpPost.setEntity(new StringEntity(_data));
            response = _httpClient.execute(httpPost);
            break;
        default:
            throw new IllegalArgumentException("Unsupported HTTP method: " + _method.name());
        }

        processEntity(response.getEntity());
    } catch (Exception e) {
        _handler.sendMessage(Message.obtain(_handler, AsyncHttpConnection.DID_ERROR, e));
    }
    ConnectionManager.getInstance().didComplete(this);
}

From source file:foam.littlej.android.app.net.MainHttpClient.java

public MainHttpClient(Context context) {
    this.context = context;
    httpParameters = new BasicHttpParams();
    httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));

    httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, "utf8");

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

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    try {/*from  ww  w  .j a  v a 2  s. c  o  m*/
        schemeRegistry.register(new Scheme("https", new TrustedSocketFactory(Preferences.domain, false), 443));
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParameters, schemeRegistry),
            httpParameters);
    httpClient.setParams(httpParameters);

}

From source file:com.pretzlav.android.net.http.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @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.
 *//* w  w w  .ja v a2  s .  com*/
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, 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 AndroidHttpClient(manager, params);
}