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:com.fujitsu.dc.test.jersey.HttpClientFactory.java

/**
 * HTTPClient?./*w  ww .  j  av a 2 s. co  m*/
 * @param type 
 * @param connectionTimeout ()0????
 * @return ???HttpClient
 */
public static HttpClient create(final String type, final int connectionTimeout) {
    if (TYPE_DEFAULT.equalsIgnoreCase(type)) {
        return new DefaultHttpClient();
    }

    SSLSocketFactory sf = null;
    try {
        if (TYPE_INSECURE.equalsIgnoreCase(type)) {
            sf = createInsecureSSLSocketFactory();
        }
    } catch (Exception e) {
        return null;
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("https", PORTHTTPS, sf));
    schemeRegistry.register(new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()));
    HttpParams params = new BasicHttpParams();
    ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
    // ClientConnectionManager cm = new
    // ThreadSafeClientConnManager(schemeRegistry);
    HttpClient hc = new DefaultHttpClient(cm, params);

    HttpParams params2 = hc.getParams();
    int timeout = TIMEOUT;
    if (connectionTimeout != 0) {
        timeout = connectionTimeout;
    }
    HttpConnectionParams.setConnectionTimeout(params2, timeout); // ?
    HttpConnectionParams.setSoTimeout(params2, timeout); // ??
    return hc;
}

From source file:br.ufg.inf.es.fs.contpatri.mobile.webservice.EnviarColeta.java

@Override
protected Void doInBackground(final Void... params) {

    /*/*from   w w w.  j av  a 2 s  .c o  m*/
     * Ajuste de timeout.
     */
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setSoTimeout(httpParams, timeout);

    /*
     * Configuraes iniciais para estabelecer uma conexo HTTP.
     */
    final DefaultHttpClient httpCliente = new DefaultHttpClient(httpParams);
    final HttpPost httpPost = new HttpPost(ListaLinks.URL_ENVIAR_COLETA);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    HttpResponse httpResponse;

    try {

        httpPost.setEntity(new StringEntity(tmbDAO.getTodosJson()));
        httpResponse = httpCliente.execute(httpPost);

        /*
         * Se a resposta ao servidor for uma de cdigo maior ou igual a 400,
         * significa que houve erro que no houve comunicao com o
         * WebService. Caso contrrio a comunicao foi bem sucedida.
         */
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            sucesso = false;
            mensagem = httpResponse.getStatusLine().getReasonPhrase();
        } else {

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            StringBuilder builder = new StringBuilder();

            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }

            final JSONObject json = new JSONObject(builder.toString());

            sucesso = json.getBoolean("sucesso");
            mensagem = json.getString("mensagem");

        }

    } catch (final UnsupportedEncodingException e) {
        Log.e(EnviarColeta.class.getSimpleName(), "", e);
    } catch (final ClientProtocolException e) {
        Log.e(EnviarColeta.class.getSimpleName(), "", e);
    } catch (final IOException e) {
        Log.e(EnviarColeta.class.getSimpleName(), "", e);
    } catch (final JSONException e) {
        Log.e(EnviarColeta.class.getSimpleName(), "", e);
    }

    return null;
}

From source file:nl.hardijzer.bitonsync.client.NetworkUtilities.java

/**
 * Configures the httpClient to connect to the URL provided.
 *///from w w  w. j  a v  a  2  s. c  o m
public static void maybeCreateHttpClient() {
    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();
        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, REGISTRATION_TIMEOUT);
        ConnManagerParams.setTimeout(params, REGISTRATION_TIMEOUT);
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet/*  w  w  w  .j av a 2 s.  c  o m*/
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

public static MessageResponse call(MessageRequest msgRequest, String appToken, String authToken,
        Long responseTimeout) throws ConnectionException, ProtocolException, SecurityException {
    MessageResponse msgResponse = null;//from  w  w w.j  av  a  2  s  . c  o m

    try {
        HttpClient httpClient;

        if (responseTimeout != null && responseTimeout > 0) {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, responseTimeout.intValue());
            HttpConnectionParams.setSoTimeout(httpParameters, responseTimeout.intValue());
            httpClient = HttpsClientBuilder.getNewHttpClient(httpParameters);
        } else {
            httpClient = HttpsClientBuilder.getNewHttpClient(null);
        }

        HttpRequestBase request = buildRequest(msgRequest, appToken, authToken);

        HttpResponse response = httpClient.execute(request);

        int status = response.getStatusLine().getStatusCode();

        if (status == Constants.CODE_SECURITY_ERROR) {
            throw new SecurityException("Invalid token");
        }
        if (status != 200) {
            throw new ProtocolException("Internal error: " + status);
        }

        long timestamp = AndroidHttpClient
                .parseDate(response.getFirstHeader(ResponseHeader.DATE.toString()).getValue());
        msgResponse = new MessageResponse(status, timestamp);

        // file
        if (msgRequest.isRequestFile()) {
            msgResponse.setFileContent(Utils.responseContentToByteArray(response.getEntity().getContent()));
        } else {

            // content
            String result = Utils.responseContentToString(response.getEntity().getContent());
            if (result != null) {
                msgResponse.setBody(result);
            }
        }
    } catch (SecurityException e) {
        throw e;
    } catch (SocketTimeoutException e) {
        throw new ConnectionException(e.getMessage());
    } catch (ClientProtocolException e) {
        throw new ProtocolException(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new ConnectionException(e.getMessage());
    } catch (URISyntaxException e) {
        throw new ProtocolException(e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        throw new ProtocolException(e.getMessage());
    }

    return msgResponse;
}

From source file:com.sumologic.log4j.SumoLogicAppender.java

@Override
public void activateOptions() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, socketTimeout);
    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(), params);
}

From source file:com.starbucks.apps.HttpUtils.java

private static DefaultHttpClient getHttpClient(HttpInvocationContext context) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }//from   w  w  w. java  2 s  .co  m
    });
    client.addRequestInterceptor(context);
    client.addResponseInterceptor(context);
    return client;
}

From source file:com.todoroo.andlib.service.HttpRestClient.java

@SuppressWarnings("nls")
public HttpRestClient() {
    DependencyInjectionService.getInstance().inject(this);

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

    params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    cm = new ThreadSafeClientConnManager(params, schemeRegistry);
}

From source file:com.extradea.framework.images.workers.DownloadWorker.java

public DownloadWorker() {
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);
    client = new DefaultHttpClient(httpParams);
    client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
}

From source file:cn.clxy.upload.ApacheHCUploader.java

/**
 * The timeout should be adjusted by network condition.
 * @return//from  ww w . j ava  2s  .  c o  m
 */
private static HttpClient createClient() {

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

    PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schReg);
    ccm.setMaxTotal(Config.maxUpload);

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
    HttpConnectionParams.setSoTimeout(params, Config.timeOut);

    return new DefaultHttpClient(ccm, params);
}