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.book.jtm.chap03.HttpClientDemo.java

private static HttpParams defaultHttpParams() {
    HttpParams mDefaultParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(mDefaultParams, 10000);
    HttpConnectionParams.setSoTimeout(mDefaultParams, 15000);
    HttpConnectionParams.setTcpNoDelay(mDefaultParams, true);
    // ?false//from  w  w  w. j  a v a 2s .c  o m
    HttpConnectionParams.setStaleCheckingEnabled(mDefaultParams, false);
    // ???
    HttpProtocolParams.setVersion(mDefaultParams, HttpVersion.HTTP_1_1);
    // ??
    HttpProtocolParams.setUseExpectContinue(mDefaultParams, true);
    return mDefaultParams;
}

From source file:com.vrs.qrw100s.NetworkReader.java

@Override
public void run() {
    Thread.currentThread().setName("Network Reader");

    HttpResponse res;//from   ww  w.jav  a 2 s.c  o m
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpParams httpParams = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);

    Log.d(TAG, "1. Sending http request");
    try {
        res = httpclient.execute(new HttpGet(URI.create(myURL)));
        Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode());
        if (res.getStatusLine().getStatusCode() == 401) {
            return;
        }

        DataInputStream bis = new DataInputStream(res.getEntity().getContent());
        ByteArrayOutputStream jpgOut = new ByteArrayOutputStream(10000);

        int prev = 0;
        int cur;

        while ((cur = bis.read()) >= 0 && _runThread) {
            if (prev == 0xFF && cur == 0xD8) {
                // reset the output stream
                if (!skipFrame) {
                    jpgOut.reset();
                    jpgOut.write((byte) prev);
                }
            }

            if (!skipFrame) {
                if (jpgOut != null) {
                    jpgOut.write((byte) cur);
                }
            }

            if (prev == 0xFF && cur == 0xD9) {
                if (!skipFrame) {
                    synchronized (curFrame) {
                        curFrame = jpgOut.toByteArray();
                    }

                    skipFrame = true;

                    Message threadMessage = mainHandler.obtainMessage();
                    threadMessage.obj = curFrame;
                    mainHandler.sendMessage(threadMessage);
                } else {
                    if (skipNum < frameDecrement) {
                        skipNum++;
                    } else {
                        skipNum = 0;
                        skipFrame = false;
                    }
                }

            }
            prev = cur;
        }
    } catch (ClientProtocolException e) {
        Log.d(TAG, "Request failed-ClientProtocolException", e);
    } catch (IOException e) {
        Log.d(TAG, "Request failed-IOException", e);
    }

}

From source file:simple.crawler.http.HttpClientFactory.java

public static DefaultHttpClient createNewDefaultHttpClient() {
    ////from www. jav a  2s. c  o  m
    HttpParams params = new BasicHttpParams();

    //Determines the connection timeout
    HttpConnectionParams.setConnectionTimeout(params, 1 * 60 * 1000);

    //Determines the socket timeout
    HttpConnectionParams.setSoTimeout(params, 1 * 60 * 1000);

    //Determines whether stale connection check is to be used
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    //The Nagle's algorithm tries to conserve bandwidth by minimizing the number of segments that are sent. 
    //When application wish to decrease network latency and increase performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY)
    //Data will be sent earlier, at the cost of an increase in bandwidth consumption
    HttpConnectionParams.setTcpNoDelay(params, true);

    //
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params,
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.4) Gecko/20100513 Firefox/3.6.4");

    //Create and initialize scheme registry
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    PoolingClientConnectionManager pm = new PoolingClientConnectionManager(schemeRegistry);

    //
    DefaultHttpClient httpclient = new DefaultHttpClient(pm, params);
    //ConnManagerParams.setMaxTotalConnections(params, MAX_HTTP_CONNECTION);
    //ConnManagerParams.setMaxConnectionsPerRoute(params, defaultConnPerRoute);
    //ConnManagerParams.setTimeout(params, 1 * 60 * 1000);
    httpclient.getParams().setParameter("http.conn-manager.max-total", MAX_HTTP_CONNECTION);
    ConnPerRoute defaultConnPerRoute = new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 4;
        }
    };
    httpclient.getParams().setParameter("http.conn-manager.max-per-route", defaultConnPerRoute);
    httpclient.getParams().setParameter("http.conn-manager.timeout", 1 * 60 * 1000L);
    httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);
    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    //
    HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 2) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    httpclient.setHttpRequestRetryHandler(retryHandler);

    HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip, deflate");
            }
        }
    };

    HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header header = entity.getContentEncoding();
            if (header != null) {
                HeaderElement[] codecs = header.getElements();
                for (int i = 0; i < codecs.length; i++) {
                    String codecName = codecs[i].getName();
                    if ("gzip".equalsIgnoreCase(codecName)) {
                        response.setEntity(new GzipDecompressingEntity(entity));
                        return;
                    } else if ("deflate".equalsIgnoreCase(codecName)) {
                        response.setEntity(new DeflateDecompressingEntity(entity));
                        return;
                    }
                }
            }
        }
    };

    httpclient.addRequestInterceptor(requestInterceptor);
    httpclient.addResponseInterceptor(responseInterceptor);
    httpclient.setRedirectStrategy(new DefaultRedirectStrategy());

    return httpclient;
}

From source file:org.odk.voice.storage.InstanceUploader.java

public int uploadInstance(int instanceId) {
    // configure connection
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
    HttpClientParams.setRedirecting(params, false);

    // setup client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpPost httppost = new HttpPost(serverUrl);

    MultipartEntity entity = new MultipartEntity();

    // using file storage

    //        // get instance file
    //        File instanceDir = new File(instancePath);
    ///*from www  . j a  v a  2  s  . com*/
    //        // find all files in parent directory
    //        File[] files = instanceDir.listFiles();
    //        if (files == null) {
    //            log.warn("No files to upload in " + instancePath);
    //        }

    // mime post
    //          for (int j = 0; j < files.length; j++) {
    //              File f = files[j];
    //              if (f.getName().endsWith(".xml")) {
    //                  // uploading xml file
    //                  entity.addPart("xml_submission_file", new FileBody(f,"text/xml"));
    //                  log.info("added xml file " + f.getName());
    //              } else if (f.getName().endsWith(".wav")) {
    //                  // upload audio file
    //                  entity.addPart(f.getName(), new FileBody(f, "audio/wav"));
    //                  log.info("added audio file" + f.getName());
    //              } else {
    //                log.info("unsupported file type, not adding file: " + f.getName());
    //              }
    //          }

    // using database storage      
    DbAdapter dba = null;
    try {
        dba = new DbAdapter();
        byte[] xml = dba.getInstanceXml(instanceId);
        if (xml == null) {
            log.error("No XML for instanceId " + instanceId);
            return STATUS_ERROR;
        }
        entity.addPart("xml_submission_file", new InputStreamBody(new ByteArrayInputStream(xml), "text/xml"));
        List<InstanceBinary> binaries = dba.getBinariesForInstance(instanceId);
        for (InstanceBinary b : binaries) {
            entity.addPart(b.name, new InputStreamBody(new ByteArrayInputStream(b.binary), b.mimeType, b.name));
        }
    } catch (SQLException e) {
        log.error("SQLException uploading instance", e);
        return STATUS_ERROR;
    } finally {
        dba.close();
    }

    httppost.setEntity(entity);

    // prepare response and return uploaded
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IOException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IllegalStateException e) {
        log.error(e);
        return STATUS_ERROR;
    }

    // check response.
    // TODO: This isn't handled correctly.
    String responseUrl = null;
    Header[] h = response.getHeaders("Location");
    if (h != null && h.length > 0) {
        responseUrl = h[0].getValue();
    } else {
        log.error("Location header was absent");
        return STATUS_ERROR;
    }
    int responseCode = response.getStatusLine().getStatusCode();
    log.info("Response code:" + responseCode);

    // verify that your response came from a known server
    if (responseUrl != null && serverUrl.contains(responseUrl) && responseCode == 201) {
        return STATUS_OK;
    }
    return STATUS_ERROR;
}

From source file:com.android.dumprendertree2.FsUtils.java

private static HttpClient getHttpClient() {
    if (sHttpClient == null) {
        HttpParams params = new BasicHttpParams();

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(//from  w w  w .j av  a2s . c  o m
                new Scheme("http", PlainSocketFactory.getSocketFactory(), ForwarderManager.HTTP_PORT));
        schemeRegistry.register(
                new Scheme("https", SSLSocketFactory.getSocketFactory(), ForwarderManager.HTTPS_PORT));

        ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
        sHttpClient = new DefaultHttpClient(connectionManager, params);
        HttpConnectionParams.setSoTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
        HttpConnectionParams.setConnectionTimeout(sHttpClient.getParams(), HTTP_TIMEOUT_MS);
    }
    return sHttpClient;
}

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

@Override
public InputStream getInputStream() throws IOException {
    if (!isBuild()) {
        throw new IllegalArgumentException(REQUEST_IS_NOT_BUILDED);
    }/*from  w  ww . jav  a  2 s . c om*/
    startTime = System.currentTimeMillis();

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

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

    printToLogUrl();

    return getResponce(httpPost);
}

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

@Override
public InputStream getInputStream() throws IOException {
    if (!isBuild()) {
        throw new IllegalArgumentException(REQUEST_IS_NOT_BUILDED);
    }// w w w .  j a va 2s  . c o m
    startTime = System.currentTimeMillis();

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

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

    printToLogUrl();

    return getResponce(httpPost);
}

From source file:HttpsRequestDemo.java

private String sentHttpPostRequest(String requestMsg) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    // SSLSocketFactory
    registerSSLSocketFactory(httpclient);

    // /*from  w  ww .j  a  v  a  2s.co  m*/
    int timeout = 60000;
    HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeout);

    // post
    HttpPost httppost = new HttpPost(targetURL);

    // 
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // 
    params.add(new BasicNameValuePair("messageRouter", messageRouter));
    // 
    params.add(new BasicNameValuePair("tradingPartner", partnerCode));
    // 
    params.add(new BasicNameValuePair("documentProtocol", documentProtocol));
    // xml
    params.add(new BasicNameValuePair("requestMessage", requestMsg));

    // UTF-8
    HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
    httppost.setEntity(request);

    // xmlxml
    HttpResponse httpResponse = httpclient.execute(httppost);
    HttpEntity entity = httpResponse.getEntity();
    String result = null;
    if (entity != null) {
        result = EntityUtils.toString(entity);
    }

    return result;
}

From source file:com.snda.mymarket.providers.downloads.HttpClientStack.java

@Override
public HttpResponse performRequest(HttpUriRequest httpRequest) throws IOException {
    HttpParams httpParams = httpRequest.getParams();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MSECONDES);
    HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MSECONDES);

    return mClient.execute(httpRequest);
}

From source file:server.web.HttpRequestHelper.java

private static DefaultHttpClient getHttpClient() {
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    return new DefaultHttpClient(httpParameters);
}