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.ctyun.amazonaws.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from  w  w w  .j  a va 2  s .c  o  m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }

    /* Set connection manager */
    ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory
            .createThreadSafeClientConnManager(config, httpClientParams);
    DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams);
    httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());

        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);

        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty("com.amazonaws.sdk.disableCertChecking") != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        AmazonHttpClient.log
                .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        String proxyDomain = config.getProxyDomain();
        String proxyWorkstation = config.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    return httpClient;
}

From source file:com.jug6ernaut.android.utilites.FileDownloader.java

/**
 * still has issues...//  w ww . j  a va2s.  c o m
 * 
 * @param inputUrl
 * @param outputFile
 * @return
 */

@Deprecated
public File downloadFileNew(File inputUrl, File outputFile) {
    OutputStream out = null;
    InputStream fis = null;

    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 2500;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 2500;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    File dir = outputFile.getParentFile();
    dir.mkdirs();

    try {

        HttpGet httpRequest = new HttpGet(stringFromFile(inputUrl));
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse response = httpClient.execute(httpRequest);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            out = new BufferedOutputStream(new FileOutputStream(outputFile));
            long total = entity.getContentLength();
            fis = entity.getContent();

            if (total > 1 || true)
                startTalker(total);
            else {
                throw new IOException("Content null");
            }
            long progress = 0;

            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = fis.read(buffer)) != -1) {

                out.write(buffer, 0, length);

                progressTalker(length);
                progress += length;
            }

            /*
            for (int b; (b = fis.read()) != -1;) {
               out.write(b);
               progress+=b;
               progressTalker(b);
            }
            */

            finishTalker(progress);
        }
    } catch (Exception e) {
        cancelTalker(e);
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (out != null) {
                out.flush();
                out.close();
            }
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return outputFile;
}

From source file:riddimon.android.asianetautologin.HttpManager.java

private HttpManager(Boolean debug, String version) {
    // Set basic data
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, true);
    HttpProtocolParams.setUserAgent(params, HttpUtils.userAgent);

    // Make pool//from   www.j  a  va  2 s. co m
    ConnPerRoute connPerRoute = new ConnPerRouteBean(12);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    ConnManagerParams.setMaxTotalConnections(params, 20);

    // Set timeout
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Some client params
    HttpClientParams.setRedirecting(params, false);

    // Register http/s schemas!
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (debug) {
        // Install the all-trusting trust manager
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustManagers = new X509TrustManager[1];
        trustManagers[0] = new TrustAllManager();

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            schReg.register(new Scheme("https", (SocketFactory) sc.getSocketFactory(), 443));
        } catch (Exception e) {
            ;
        }
    } else {
        schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    }
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    client = new DefaultHttpClient(conMgr, params);

}

From source file:ua.at.tsvetkov.data_processor.requests.MultipartRequest.java

@Override
public InputStream getInputStream() throws IOException {
    if (!isBuild()) {
        throw new IllegalArgumentException(REQUEST_IS_NOT_BUILDED);
    }/*  w w w  . ja  v a  2s  .  com*/
    startTime = System.currentTimeMillis();

    HttpConnectionParams.setConnectionTimeout(httpParameters, configuration.getTimeout());
    HttpConnectionParams.setSoTimeout(httpParameters, configuration.getTimeout());

    HttpPost httpPost = new HttpPost(toString());
    httpPost.setEntity(entity);
    httpPost.setParams(httpParameters);
    if (header != null) {
        httpPost.addHeader(header);
    }

    printToLogUrl();

    return getResponce(httpPost);
}

From source file:devza.app.android.droidnetkey.FirewallAction.java

public FirewallAction(Context context, boolean status, boolean refresh) {
    this.context = context;
    this.fwstatus = status;
    this.refresh = refresh;

    client = new StbFwHttpsClient(this.context);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, TIMEOUT);

    client.setParams(params);/*from   ww  w .  ja va2 s .  c o m*/

    if (!refresh)
        this.context.bindService(new Intent(this.context, ConnectionService.class), mConnection,
                Context.BIND_AUTO_CREATE);
}

From source file:com.allblacks.utils.web.HttpUtil.java

private HttpUtil() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 5000);
    HttpConnectionParams.setSoTimeout(params, 5000);
}

From source file:org.jinos.transport.HttpTransport.java

/**
 * Call the service//from   w  ww.ja va2  s  . c om
 *
 * @param <T> The return type
 * @param envelope The request envelope
 * @param resultClass The class of the result in the response
 * @param httpHeaders The custom Http headers
 * @return The response
 * @throws Exception An exception
 */

public <T> T call(String reqXMLString, Class<T> resultClass, Map<String, String> httpHeaders) throws Exception {
    try {
        long start = System.nanoTime();

        HttpPost post = new HttpPost(this.getUrl());
        post.setEntity(new StringEntity(reqXMLString));
        post.setHeader("Content-type", "text/xml; charset=UTF-8");
        if (httpHeaders != null) {
            for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        /*  if (this.getUsername() != null && this.getPassword() != null)
          {
            post.addHeader("Authorization", "Basic " + Base64Encoder.encodeString(this.getUsername() + ":" + this.getPassword()));
          }*/

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
        HttpConnectionParams.setSoTimeout(httpParameters, 6000);

        /* if (this.isDEBUG())
         {
           Log.i(this.getClass().getSimpleName(), "Request: " + envelope.toString());
         }*/

        HttpClient client = new DefaultHttpClient(httpParameters);
        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();

        Log.i(this.getClass().getSimpleName(), "The server has been replied. "
                + ((System.nanoTime() - start) / 1000) + "us, status is " + status);
        start = System.nanoTime();

        InputStream is = response.getEntity().getContent();

        if (true) {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                sb.append(line);
                sb.append("\n");
            }
            Log.i(this.getClass().getSimpleName(), "Response: " + sb.toString());
            br.close();
            isr.close();
            is.close();

            is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));

            Log.i(this.getClass().getSimpleName(),
                    "DEBUG mode delay: " + ((System.nanoTime() - start) / 1000) + "us");
            start = System.nanoTime();
        }

        /*  GenericHandler handler = new GenericHandler(resultClass, this.isDEBUG());
          if (status == 200)
          {
            handler.parseWithPullParser(is);
          } else
          {
            throw new Exception("Can't parse the response, status: " + status);
          }
                
          Log.i(this.getClass().getSimpleName(), "The reply has been parsed: " + ((System.nanoTime() - start) / 1000) + "us");
        */
        //return (T) handler.getObject();
        return null;
    }

    catch (Exception e) {
        Log.e(this.getClass().getSimpleName(), e.toString(), e);
        throw e;
    }

}

From source file:net.sourceforge.subsonic.ajax.LyricsService.java

private String executeGetRequest(String url) throws IOException {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
    HttpGet method = new HttpGet(url);
    try {/*  www .ja v a  2 s  .  c o  m*/

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        return client.execute(method, responseHandler);

    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.openremote.android.console.util.HTTPUtil.java

/**
 * Down load file and store it in local context.
 * /*from  w ww .  j a  v  a 2 s  .  com*/
 * @param serverUrl the current server url
 * @param fileName the file name for downloading
 * 
 * @return the int
 */
private static int downLoadFile(Context context, String serverUrl, String fileName) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient client = new DefaultHttpClient(params);
    int statusCode = ControllerException.CONTROLLER_UNAVAILABLE;
    try {
        URL uri = new URL(serverUrl);
        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            client.getConnectionManager().getSchemeRegistry().register(sch);
        }
        HttpGet get = new HttpGet(serverUrl);
        SecurityUtil.addCredentialToHttpRequest(context, get);
        HttpResponse response = client.execute(get);
        statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == Constants.HTTP_SUCCESS) {
            FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            InputStream is = response.getEntity().getContent();
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                fOut.write(buf, 0, len);
            }
            fOut.close();
            is.close();
        }
    } catch (MalformedURLException e) {
        Log.e("OpenRemote-HTTPUtil", "Create URL fail:" + serverUrl);
    } catch (IllegalArgumentException e) {
        Log.e("OpenRemote-IllegalArgumentException",
                "Download file " + fileName + " failed with URL: " + serverUrl, e);
    } catch (ClientProtocolException cpe) {
        Log.e("OpenRemote-ClientProtocolException",
                "Download file " + fileName + " failed with URL: " + serverUrl, cpe);
    } catch (IOException ioe) {
        Log.e("OpenRemote-IOException", "Download file " + fileName + " failed with URL: " + serverUrl, ioe);
    }
    return statusCode;
}

From source file:com.pannous.es.reindex.MySearchResponseJson.java

public MySearchResponseJson(String searchHost, int searchPort, String searchIndexName, String searchType,
        String filter, String credentials, int hitsPerPage, boolean withVersion, int keepTimeInMinutes) {
    if (!searchHost.startsWith("http"))
        searchHost = "http://" + searchHost;
    this.host = searchHost;
    this.port = searchPort;
    this.withVersion = withVersion;
    keepMin = keepTimeInMinutes;//w  w  w.j  av  a  2  s.  c o  m
    bufferedHits = new ArrayList<MySearchHit>(hitsPerPage);
    PoolingClientConnectionManager connManager = new PoolingClientConnectionManager();
    connManager.setMaxTotal(10);

    BasicHttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    client = new DefaultHttpClient(connManager, params);

    // does not work!? client.getParams().setParameter("Authorization", "Basic " + credentials);
    if (credentials != null)
        this.credentials = credentials;

    // initial query to get scroll id for our specific search
    try {
        String url = searchHost + ":" + searchPort + "/" + searchIndexName + "/" + searchType
                + "/_search?search_type=scan&scroll=" + keepMin + "m&size=" + hitsPerPage;

        String query;
        if (filter == null || filter.isEmpty())
            query = "{ \"query\" : {\"match_all\" : {}}, \"fields\" : [\"_source\", \"_parent\"]}";
        else
            query = "{ \"filter\" : " + filter + ", \"fields\" : [\"_source\", \"_parent\"] }";

        JSONObject res = doPost(url, query);
        scrollId = res.getString("_scroll_id");
        totalHits = res.getJSONObject("hits").getLong("total");
    } catch (JSONException ex) {
        throw new RuntimeException(ex);
    }
}