Example usage for org.apache.http.params CoreConnectionPNames SO_TIMEOUT

List of usage examples for org.apache.http.params CoreConnectionPNames SO_TIMEOUT

Introduction

In this page you can find the example usage for org.apache.http.params CoreConnectionPNames SO_TIMEOUT.

Prototype

String SO_TIMEOUT

To view the source code for org.apache.http.params CoreConnectionPNames SO_TIMEOUT.

Click Source Link

Usage

From source file:com.android.wako.net.AsyncHttpPost.java

public boolean process() {
    try {/*ww w  .ja  va  2s.  c  om*/
        //            LogUtil.d(Tag, "---process---url="+url+"?"+getParames());
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        //            LogUtil.d(AsyncHttpPost.class.getName(),
        //                    "AsyncHttpPost  request to url :" + url);

        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }

            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();
            return true;

        } else {
            mRetStatus = ResStatus.Error_Code;
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            //                ret = ErrorUtil.errorJson("ERROR.HTTP.001",
            //                        exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (IllegalArgumentException e) {
        mRetStatus = ResStatus.Error_IllegalArgument;
        //            RequestException exception = new RequestException(
        //                    RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        mRetStatus = ResStatus.Error_Connect_Timeout;
        //            RequestException exception = new RequestException(
        //                    RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        mRetStatus = ResStatus.Error_Socket_Timeout;
        //            RequestException exception = new RequestException(
        //                    RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE);
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        mRetStatus = ResStatus.Error_Unsupport_Encoding;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        mRetStatus = ResStatus.Error_HttpHostConnect;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.CONNECT_EXCEPTION, "");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        mRetStatus = ResStatus.Error_Client_Protocol;
        e.printStackTrace();
        //            RequestException exception = new RequestException(
        //                    RequestException.CLIENT_PROTOL_EXCEPTION, "??");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        mRetStatus = ResStatus.Error_IOException;
        //            RequestException exception = new RequestException(
        //                    RequestException.IO_EXCEPTION, "??");
        //            ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } catch (Exception e) {
        mRetStatus = ResStatus.Error_IOException;
        e.printStackTrace();
    }
    return false;
}

From source file:com.adavr.http.Client.java

public Client() {
    httpClient = new DefaultHttpClient(new BasicClientConnectionManager());
    localContext = new BasicHttpContext();
    byteStream = new ByteArrayOutputStream();

    CookieStore cookieStore = new BasicCookieStore();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        @Override//from  ww  w  .j  ava2  s.c  o  m
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header ceheader = entity.getContentEncoding();
            if (ceheader != null) {
                HeaderElement[] codecs = ceheader.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });

    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEFAULT_TIMEOUT);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, DEFAULT_USER_AGENT);
    HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {

        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= DEFAULT_RETRY) {
                // Do not retry if over max retry count
                return false;
            }
            System.out.println(exception.getClass().getName());
            if (exception instanceof NoHttpResponseException) {
                // Retry if the server dropped connection on us
                return true;
            }
            if (exception instanceof SSLHandshakeException) {
                // Do not retry on SSL handshake exception
                return false;
            }
            HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        }
    };

    httpClient.setHttpRequestRetryHandler(myRetryHandler);
}

From source file:org.energy_home.jemma.utils.rest.RestClient.java

private RestClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    // allow working with all hostname server (hostname verification default turned off)
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    // TODO: check for final values
    // Decrease max total connection to 10 (default is 20)
    connectionManager.setMaxTotal(10);//from   w w w.j  a  v  a  2 s  .  c o m
    // Increase default max connection per route to 5 (default is 2)
    connectionManager.setDefaultMaxPerRoute(10);
    // // Increase max connections for localhost:80 to 50
    // HttpHost localhost = new HttpHost("locahost", 80);
    // cm.setMaxForRoute(new HttpRoute(localhost), 50);
    // // Increase max connections for a specific host to 10
    // connectionManager.setMaxForRoute(new HttpRoute(httpHost), 10);

    httpClient = new DefaultHttpClient(connectionManager);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    // Default to HTTP 1.0
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    // The time it takes to open TCP connection.
    // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
    // 15000);
    // Timeout when server does not send data.
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

    // Some tuning that is not required for bit tests.
    // httpClient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
    // false);
    // httpClient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY,
    // true);
    httpContext = new BasicHttpContext();
}

From source file:com.couchbase.client.ViewConnection.java

/**
 * Create ViewNode connections and queue them up for connect.
 *
 * This method also defines the connection params for each connection,
 * including the default settings like timeouts and the user agent string.
 *
 * @param addrs addresses of all the nodes it should connect to.
 * @return Returns a list of the ViewNodes.
 * @throws IOException// w w w. ja v a 2s .  c om
 */
private List<ViewNode> createConnections(List<InetSocketAddress> addrs) throws IOException {

    List<ViewNode> nodeList = new LinkedList<ViewNode>();

    for (InetSocketAddress a : addrs) {
        HttpParams params = new SyncBasicHttpParams();
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
                .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
                .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                .setParameter(CoreProtocolPNames.USER_AGENT, "Couchbase Java Client 1.0.2");

        HttpProcessor httpproc = new ImmutableHttpProcessor(
                new HttpRequestInterceptor[] { new RequestContent(), new RequestTargetHost(),
                        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue(), });

        AsyncNHttpClientHandler protocolHandler = new AsyncNHttpClientHandler(httpproc,
                new MyHttpRequestExecutionHandler(), new DefaultConnectionReuseStrategy(),
                new DirectByteBufferAllocator(), params);
        protocolHandler.setEventListener(new EventLogger());

        AsyncConnectionManager connMgr = new AsyncConnectionManager(new HttpHost(a.getHostName(), a.getPort()),
                NUM_CONNS, protocolHandler, params, new RequeueOpCallback(this));
        getLogger().info("Added %s to connect queue", a.getHostName());

        ViewNode node = connFactory.createViewNode(a, connMgr);
        node.init();
        nodeList.add(node);
    }

    return nodeList;
}

From source file:jp.ne.sakura.kkkon.android.exceptionhandler.DefaultUploaderWeb.java

public static void upload(final Context context, final File file, final String url) {
    terminate();/*from w ww  . j av a  2 s. c om*/

    thread = new Thread(new Runnable() {

        @Override
        public void run() {
            Log.d(TAG, "upload thread tid=" + android.os.Process.myTid());
            try {
                //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                Log.d(TAG, "fng=" + Build.FINGERPRINT);
                final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                HttpPost httpPost = new HttpPost(url);
                //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                DefaultHttpClient httpClient = new DefaultHttpClient();
                Log.d(TAG, "socket.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                Log.d(TAG, "connection.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000));
                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                        new Integer(5 * 1000));
                Log.d(TAG, "socket.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                Log.d(TAG, "connection.timeout="
                        + httpClient.getParams().getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                // <uses-permission android:name="android.permission.INTERNET"/>
                // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                HttpResponse response = httpClient.execute(httpPost);
                Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
            } finally {
                ExceptionHandler.clearReport();
            }
            Log.d(TAG, "upload finish");
        }
    });
    thread.setName("upload crash");

    thread.start();
    if (USE_DIALOG) {
        final AlertDialog.Builder alertDialogBuilder = setupAlertDialog(context);
        if (null != alertDialogBuilder) {
            alertDialogBuilder.setCancelable(false);

            final AlertDialog alertDialog = alertDialogBuilder.show();

            /*
            while ( thread.isAlive() )
            {
            Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() );
            if ( ! thread.isAlive() )
            {
                break;
            }
                    
            {
                try
                {
                    Thread.sleep( 1 * 1000 );
                }
                catch ( InterruptedException e )
                {
                    Log.d( TAG, "got exception", e );
                }
            }
                    
            if ( null != alertDialog )
            {
                if ( alertDialog.isShowing() )
                {
                }
                else
                {
                    if ( ! thread.isAlive() )
                    {
                        break;
                    }
                    alertDialog.show();
                }
            }
                    
            if ( ! Thread.State.RUNNABLE.equals(thread.getState()) )
            {
                break;
            }
                    
            }
                    
            if ( null != alertDialog )
            {
            alertDialog.dismiss();
            }
            */
        }

        try {
            thread.join(); // must call. leak handle...
            thread = null;
        } catch (InterruptedException e) {
            Log.d(TAG, "got Exception", e);
        }
    }

}

From source file:com.nextgis.maplib.datasource.ngw.Connection.java

public HttpClient getHttpClient() {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, APP_USER_AGENT);
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT_CONNECTION);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT_SOKET);
    httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);

    return httpclient;
}

From source file:org.apache.marmotta.ldclient.services.ldclient.LDClient.java

public LDClient(ClientConfiguration config) {
    log.info("Initialising Linked Data Client Service ...");

    this.config = config;

    endpoints = new ArrayList<>();
    for (Endpoint endpoint : defaultEndpoints) {
        endpoints.add(endpoint);/*from   w  w  w  . j a  va  2  s . c om*/
    }
    endpoints.addAll(config.getEndpoints());

    Collections.sort(endpoints);
    if (log.isInfoEnabled()) {
        for (Endpoint endpoint : endpoints) {
            log.info("- LDClient Endpoint: {}", endpoint.getName());
        }
    }

    providers = new ArrayList<>();
    for (DataProvider provider : defaultProviders) {
        providers.add(provider);
    }
    providers.addAll(config.getProviders());
    if (log.isInfoEnabled()) {
        for (DataProvider provider : providers) {
            log.info("- LDClient Provider: {}", provider.getName());
        }
    }

    retrievalSemaphore = new Semaphore(config.getMaxParallelRequests());

    if (config.getHttpClient() != null) {
        log.debug("Using HttpClient provided in the configuration");
        this.client = config.getHttpClient();
    } else {
        log.debug("Creating default HttpClient based on the configuration");

        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache Marmotta LDClient");

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

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

        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, null, null);
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", 443, sf));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(20);
        cm.setDefaultMaxPerRoute(10);

        DefaultHttpClient client = new DefaultHttpClient(cm, httpParams);
        client.setRedirectStrategy(new LMFRedirectStrategy());
        client.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        idleConnectionMonitorThread = new IdleConnectionMonitorThread(client.getConnectionManager());
        idleConnectionMonitorThread.start();

        this.client = client;
    }
}

From source file:org.andstatus.app.net.HttpConnectionBasic.java

/**
 * Execute a GET request against the Twitter REST API.
 * /*from   w  w w .java2 s .  co m*/
 * @param url
 * @return String
 * @throws ConnectionException
 */
@Override
public JSONTokener getRequest(HttpGet getMethod) throws ConnectionException {
    JSONTokener jso = null;
    String response = null;
    boolean ok = false;
    int statusCode = 0;
    HttpClient client = HttpApacheUtils.getHttpClient();
    try {
        getMethod.setHeader("User-Agent", HttpConnection.USER_AGENT);
        getMethod.addHeader("Authorization", "Basic " + getCredentials());
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                MyPreferences.getConnectionTimeoutMs());
        client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                MyPreferences.getConnectionTimeoutMs());
        HttpResponse httpResponse = client.execute(getMethod);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        response = retrieveInputStream(httpResponse.getEntity());
        jso = new JSONTokener(response);
        ok = true;
    } catch (Exception e) {
        MyLog.e(this, "getRequest", e);
        throw new ConnectionException(e);
    } finally {
        getMethod.abort();
    }
    parseStatusCode(statusCode);
    if (!ok) {
        jso = null;
    }
    return jso;
}

From source file:com.facebook.stetho.server.LocalSocketHttpServer.java

private HttpParams createParams() {
    return new BasicHttpParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Stetho")
            .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, "HTTP/1.1");
}