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.mobicage.rogerthat.util.http.HTTPUtil.java

public static HttpClient getHttpClient(int connectionTimeout, int socketTimeout, final int retryCount) {
    final HttpParams params = new BasicHttpParams();

    HttpConnectionParams.setStaleCheckingEnabled(params, true);
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);

    HttpClientParams.setRedirecting(params, false);

    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    if (shouldUseTruststore()) {
        KeyStore trustStore = loadTrustStore();

        SSLSocketFactory socketFactory;
        try {//  w  ww.  j  a v a2  s .c  om
            socketFactory = new SSLSocketFactory(null, null, trustStore);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        socketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

        Scheme sch = new Scheme("https", socketFactory, CloudConstants.HTTPS_PORT);
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    if (retryCount > 0) {
        httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return executionCount < retryCount;
            }
        });
    }
    return httpClient;
}

From source file:com.amazonaws.eclipse.core.HttpClientFactory.java

public static DefaultHttpClient create(Plugin plugin, String url) {
    HttpParams httpClientParams = new BasicHttpParams();

    IPreferenceStore preferences = AwsToolkitCore.getDefault().getPreferenceStore();

    int connectionTimeout = preferences.getInt(PreferenceConstants.P_CONNECTION_TIMEOUT);
    int socketTimeout = preferences.getInt(PreferenceConstants.P_SOCKET_TIMEOUT);

    HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpClientParams, socketTimeout);

    HttpProtocolParams.setUserAgent(httpClientParams,
            AwsClientUtils.formatUserAgentString("AWS-Toolkit-For-Eclipse", plugin));

    DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams);
    configureProxy(httpclient, url);/*from   w w  w.  j  a  v a  2s . co  m*/

    return httpclient;
}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static String getETA(String url, String fromLat, String fromLongi, String toLat, String toLongi,
        String type) {//from  ww w .  java  2  s. c o  m

    HttpPost postJob = new HttpPost(HttpHelper.domain + "getduration.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 {
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("url", url));

        infoJob.add(new BasicNameValuePair("fromLongi", fromLongi));
        infoJob.add(new BasicNameValuePair("fromLat", fromLat));
        infoJob.add(new BasicNameValuePair("toLongi", toLongi));
        infoJob.add(new BasicNameValuePair("toLat", toLat));
        infoJob.add(new BasicNameValuePair("type", type));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);

        String jsonString = HttpHelper.request(response);
        String duration = jsonString.trim();

        return duration;

    } catch (Exception ex) {
        return null;
    }

}

From source file:com.sailthru.android.sdk.impl.external.retrofit.client.ApacheClient.java

private static HttpClient createDefaultClient() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, Defaults.CONNECT_TIMEOUT_MILLIS);
    HttpConnectionParams.setSoTimeout(params, Defaults.READ_TIMEOUT_MILLIS);
    return new DefaultHttpClient(params);
}

From source file:net.giovannicapuano.galax.util.Utils.java

/**
 * Perform a HTTP POST request./*from ww w  .  j a  va 2  s . c om*/
 */
public static HttpData postData(String path, List<NameValuePair> post, Context context) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    String body = "";

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, new PersistentCookieStore(context));
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

    try {
        HttpPost httpPost = new HttpPost(context.getString(R.string.server) + path);
        httpPost.setEntity(new UrlEncodedFormEntity(post));
        HttpResponse response = httpClient.execute(httpPost, localContext);

        status = response.getStatusLine().getStatusCode();
        body = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new HttpData(status, body);
}

From source file:com.photon.phresco.Screens.HttpRequest.java

/**
 * Get the content from web url, and parse it using json parser
 *
 * @param sURL//from   w  w w . j  a v a2  s.co m
 *            : URL to hit to get the json content
 * @return InputStream
 * @throws IOException
 */
public static InputStream get(String sURL) throws IOException {

    InputStream is = null;
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpGet httpGet = new HttpGet(sURL);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity entity = httpResponse.getEntity();
    is = entity.getContent();

    return is;
}

From source file:fossasia.valentina.bodyapp.sync.Sync.java

/**
 * Method which makes all the POST calls
 * /*from www. ja  v a2  s .  co  m*/
 * @param url
 * @param json
 * @return
 */
public String POST(String url, String json, int conTimeOut, int socTimeOut) {

    InputStream inputStream = null;
    String result = "";
    try {

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut);
        HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut);
        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPost = new HttpPost(url);
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse httpResponse = httpclient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();

        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
        System.out.println(result + "result");

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingHttpClient(String URL, JSONObject jsonObjSend) {

    try {//from   w  w  w.j  a  v a 2  s  . c om
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 60 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 60 * 1000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        //httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        //httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        Log.d(TAG, "httpPostReuest = " + httpPostRequest.toString());
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        Log.d(TAG, "catch block");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    Log.d(TAG, "SendHttpPostUsingHttpClient returning null");
    return null;
}

From source file:com.huguesjohnson.retroleague.util.HttpFetch.java

public static InputStream fetch(String address, int timeout) throws MalformedURLException, IOException {
    HttpGet httpRequest = new HttpGet(URI.create(address));
    HttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpParameters = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
    HttpConnectionParams.setSoTimeout(httpParameters, timeout);
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream instream = bufHttpEntity.getContent();
    return (instream);
}

From source file:HttpConnections.RestConnFactory.java

public ResponseContents RestRequest(HttpRequestBase httprequest) throws IOException {
    HttpResponse httpResponseTemp = null;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 30000);
    this.httpclient = new DefaultHttpClient(httpParams);

    try {/*  w w w.j  a v  a  2s .co m*/
        httpResponseTemp = this.httpclient.execute(httprequest);
    } catch (IOException ex) {
        System.out.println("An error occured while executing the request. Message: " + ex);
        this.responseObj.setContents(ex.toString());
    } finally {
        if (httpResponseTemp != null) {
            this.httpResponse = httpResponseTemp;
            this.responseObj.setStatus(this.httpResponse.getStatusLine().toString());
            if (this.httpResponse.getEntity() == null
                    || this.httpResponse.getStatusLine().toString().contains("500")) {
                this.responseObj.setContents("No Content");
            } else {
                this.responseObj.setContents(EntityUtils.toString(this.httpResponse.getEntity()));
            }
        }
        this.httpclient.close();
        return this.responseObj;
    }
}