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.bright.json.JSonRequestor.java

public static List<Cookie> doLogin(String user, String pass, String myURL) {
    try {//from  www .j  ava 2 s.c om
        cmLogin loginReq = new cmLogin("login", user, pass);

        GsonBuilder builder = new GsonBuilder();

        Gson g = builder.create();
        String json = g.toJson(loginReq);

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return cookies;
        }
        EntityUtils.consume(resEntity);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return null;

}

From source file:mobi.infolife.wifitransfer.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.
 *//*from w  w w .  j  ava  2 s  .  c om*/
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);

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

    // Use a session cache for SSL sockets
    //SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);

    // 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));
    //TODO:fix 443 https support/disable for now
    //        schemeRegistry.register(new Scheme("https",
    //                SSLCertificateSocketFactory.getHttpSocketFactory(
    //                SOCKET_OPERATION_TIMEOUT, 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.wareninja.android.opensource.mongolab_sdk.common.WebService.java

public WebService() {
    HttpParams myParams = new BasicHttpParams();

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

From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFour.java

/**
 * Create a default Apache HTTP client handler.
 * //from w w w.  j  a v a  2  s.  c o  m
 * @return a default Apache HTTP client handler.
 */
private static ApacheHttpClientFourHandler createDefaultClientHander(JerseyHttpClientConfig config,
        ThreadSafeClientConnManager threadSafeClientConnManager) {

    if (threadSafeClientConnManager == null) {
        throw new IllegalArgumentException("threadSafeClientConnManager cannot be null");
    }

    HttpParams httpParams = new BasicHttpParams();

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(threadSafeClientConnManager, httpParams);

    if (config.getProxyInformation() != null) {
        HttpHost proxy = new HttpHost(config.getProxyInformation().getProxyHost(),
                config.getProxyInformation().getProxyPort(), "http");
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    HttpConnectionParams.setConnectionTimeout(httpParams,
            config == null ? 60000 : config.getConnectionTimeOut());

    // FIXME 

    //HttpParams params = new BasicHttpParams();
    //params.setParameter( ConnManagerPNames.TIMEOUT, config == null ? 50000 : config
    //.getConnectionPoolTimeOut() );

    //client.setHttpConnectionFactoryTimeout( config == null ? 0 : config.getConnectionPoolTimeOut() );
    return new ApacheHttpClientFourHandler(client, config);
}

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

/**
 * Reads TimeZone from Google Json/*from ww w . j a  va  2  s . co  m*/
 *
 * @return TimeZone JSON from Google Json or empty if cannot determine
 */
private String readTimeZoneJson() {
    StringBuilder builder = new StringBuilder();
    int year = mCalendar.get(Calendar.YEAR);
    int month = mCalendar.get(Calendar.MONTH);
    int day = mCalendar.get(Calendar.DAY_OF_MONTH);
    int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
    int minute = mCalendar.get(Calendar.MINUTE);

    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calendar.set(year, month, day, hour, minute);

    /* Gets desired time as seconds since midnight, January 1, 1970 UTC */
    Long timestamp = calendar.getTimeInMillis() / 1000;

    String url_format = "https://maps.googleapis.com/maps/api/timezone/json?location=%f,%f&timestamp=%d";
    String url = String.format(Locale.US, url_format, mLocation.latitude, mLocation.longitude, timestamp);

    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.TaxiDriver.jy.DriverQuery.java

public static JSONObject getJobInfo(String job_id) {

    HttpPost postJob = new HttpPost(HttpHelper.domain + "job.php");

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 4900;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient clientJob = new DefaultHttpClient(httpParameters);

    try {//from ww w  . j  ava  2 s.  co  m

        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("job_id", job_id));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);
        String jsonString = HttpHelper.request(response);
        JSONArray jArray = new JSONArray(jsonString);
        JSONObject json = jArray.getJSONObject(0);

        return json;
    } catch (ClientProtocolException e) {
        return null;
    } catch (IOException e) {
        return null;
    } catch (JSONException e) {
        return null;
    }

}

From source file:com.loopj.android.http.RdHttpClient.java

/**
 * Creates a new AsyncHttpClient.// ww w.  j av a  2  s . co m
 */
public RdHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

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

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

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

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });
    httpClient.clearResponseInterceptors();
    httpClient.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(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    clientHeaderMap = new HashMap<String, String>();
}

From source file:com.hoccer.api.CloudService.java

protected void setupHttpClient() {

    LOG.info("setting up http client");

    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setSoTimeout(httpParams, 70 * 1000);
    HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
    ConnManagerParams.setMaxTotalConnections(httpParams, 200);
    ConnPerRoute connPerRoute = new ConnPerRouteBean(400);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
    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);
    // ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams,
    // HttpClientWithKeystore.getSchemeRegistry());
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "utf-8");
    mHttpClient = new HttpClientWithKeystore(cm, httpParams);
    mHttpClient.getParams().setParameter("http.useragent", mConfig.getApplicationName());
    mHttpClient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    mHttpClient.setReuseStrategy(new NoConnectionReuseStrategy());
}

From source file:com.cutler.template.common.transloader.download.model.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 * /* w  w  w .j  av  a2 s . c  o  m*/
 * @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.
 */
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);

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

    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new
    // SSLSessionCache(context);

    // 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",
    // SSLCertificateSocketFactory.getHttpSocketFactory(
    // SOCKET_OPERATION_TIMEOUT, 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.abid_mujtaba.bitcoin.tracker.services.FetchPriceService.java

private static HttpClient getHttpClient() // Returns an HTTP client
{
    HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);

    return new DefaultHttpClient(params);
}