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

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

Introduction

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

Prototype

String TCP_NODELAY

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

Click Source Link

Usage

From source file:net.kseek.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();// w ww .ja v a 2  s.  c  om
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.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, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.kseek.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:com.baqr.baqrcam.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();/* w w w .j ava2  s  . c  om*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.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, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service 
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:com.wifi.brainbreaker.mydemo.http.TinyHttpServer.java

@Override
public void onCreate() {
    super.onCreate();

    mContext = getApplicationContext();/*from w ww .  j  a v a2s .c o  m*/
    mRegistry = new MHttpRequestHandlerRegistry();
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    mParams = new BasicHttpParams();
    mParams.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, "MajorKernelPanic HTTP Server");

    // Set up the HTTP protocol processor
    mHttpProcessor = new BasicHttpProcessor();
    mHttpProcessor.addInterceptor(new ResponseDate());
    mHttpProcessor.addInterceptor(new ResponseServer());
    mHttpProcessor.addInterceptor(new ResponseContent());
    mHttpProcessor.addInterceptor(new ResponseConnControl());

    // Will be used in the "Last-Modifed" entity-header field
    try {
        String packageName = mContext.getPackageName();
        mLastModified = new Date(mContext.getPackageManager().getPackageInfo(packageName, 0).lastUpdateTime);
    } catch (NameNotFoundException e) {
        mLastModified = new Date(0);
    }

    // Restores the state of the service
    mHttpPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTP_PORT, String.valueOf(mHttpPort)));
    mHttpsPort = Integer.parseInt(mSharedPreferences.getString(KEY_HTTPS_PORT, String.valueOf(mHttpsPort)));
    mHttpEnabled = mSharedPreferences.getBoolean(KEY_HTTP_ENABLED, mHttpEnabled);
    mHttpsEnabled = mSharedPreferences.getBoolean(KEY_HTTPS_ENABLED, mHttpsEnabled);

    // If the configuration is modified, the server will adjust
    mSharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);

    // Loads plugins available in the package net.majorkernelpanic.http
    for (int i = 0; i < MODULES.length; i++) {
        try {
            Class<?> pluginClass = Class
                    .forName(TinyHttpServer.class.getPackage().getName() + "." + MODULES[i]);
            Constructor<?> pluginConstructor = pluginClass.getConstructor(new Class[] { TinyHttpServer.class });
            addRequestHandler((String) pluginClass.getField("PATTERN").get(null),
                    (HttpRequestHandler) pluginConstructor.newInstance(this));
        } catch (ClassNotFoundException ignore) {
            // Module disabled
        } catch (Exception e) {
            Log.e(TAG, "Bad module: " + MODULES[i]);
            e.printStackTrace();
        }
    }

    start();

}

From source file:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*///from   w ww.  j a v  a  2  s  .co m
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.
    PoolingClientConnectionManager localConnectionManager = new PoolingClientConnectionManager();
    localConnectionManager.setMaxTotal(1);
    if (mySSLFactory != null) {
        SSLSocketFactory myFactory = new SSLSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
        Scheme myHttpsProtocol = new Scheme("https", 443, myFactory);
        localConnectionManager.getSchemeRegistry().register(myHttpsProtocol);
    }
    connectionManager = localConnectionManager;

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    // Initialize the three httpclient objects

    // dmws first
    BasicHttpParams dmwsParams = new BasicHttpParams();
    dmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    dmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    dmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    dmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    dmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localDmwsHttpClient = new DefaultHttpClient(connectionManager, dmwsParams);
    // No retries
    localDmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localDmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localDmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localDmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        localDmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    dmwsHttpClient = localDmwsHttpClient;

    // rmws
    BasicHttpParams rmwsParams = new BasicHttpParams();
    rmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
    rmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
    rmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
    rmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
    rmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    DefaultHttpClient localRmwsHttpClient = new DefaultHttpClient(connectionManager, rmwsParams);
    // No retries
    localRmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }

    });

    localRmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
    if (domainUser != null) {
        localRmwsHttpClient.getCredentialsProvider().setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }
    // Initialize proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            localRmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        localRmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    rmwsHttpClient = localRmwsHttpClient;

    // mcws
    if (meridioManifoldCFWSUrl != null) {
        BasicHttpParams mcwsParams = new BasicHttpParams();
        mcwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
        mcwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
        mcwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
        mcwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000);
        mcwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        DefaultHttpClient localMcwsHttpClient = new DefaultHttpClient(connectionManager, mcwsParams);
        // No retries
        localMcwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                return false;
            }

        });

        localMcwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy());
        if (domainUser != null) {
            localMcwsHttpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }
        // Initialize proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                localMcwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            localMcwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        mcwsHttpClient = localMcwsHttpClient;
    } else
        mcwsHttpClient = null;

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:org.frameworkset.spi.remote.http.HttpServer.java

public void start() {

    serverParams = new BasicHttpParams();
    int so_timeout = this.params.getInt("http.socket.timeout", 30);//??
    int SOCKET_BUFFER_SIZE = this.params.getInt("http.socket.buffer-size", 8 * 1024);
    boolean STALE_CONNECTION_CHECK = this.params.getBoolean("http.connection.stalecheck", false);
    boolean TCP_NODELAY = this.params.getBoolean("TCP_NODELAY", true);
    String ORIGIN_SERVER = this.params.getString("http.origin-server", "RPC-SERVER/1.1");
    int CONNECTION_TIMEOUT = this.params.getInt("http.connection.timeout", 30);
    int httpsoLinger = this.params.getInt("http.soLinger", -1);
    serverParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, so_timeout * 1000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, SOCKET_BUFFER_SIZE)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, STALE_CONNECTION_CHECK)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, TCP_NODELAY)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, ORIGIN_SERVER)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT * 1000)
            .setIntParameter(CoreConnectionPNames.SO_LINGER, httpsoLinger);

    if (!enablessl) {
        try {//  w  ww  . j a  v  a 2s  . co m
            this.startHttp();
            System.out.println("Http server is listenig at port " + port + ",ip is " + this.ip);
            System.out.println("Http server started.");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        try {
            this.startHttps();
            System.out.println("Https server is listenig at port " + port + ",ip is " + this.ip);
            System.out.println("Https server started.");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    if (this.started)
        ApplicationContext.addShutdownHook(new ShutDownHttpServer(this));
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by
 * minimizing the number of segments that are sent. When applications 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.
 *///w w w . java 2  s . c  om
public void setTcpNoDelay(boolean enable) {
    client.getParams().setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, enable);
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Tests if Nagle's algorithm is to be used.
 */// w w w  .  ja v a 2 s. c  om
public boolean getTcpNoDelay() {
    return client.getParams().getBooleanParameter(CoreConnectionPNames.TCP_NODELAY, false);
}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpAsyncClient.java

private void initialize() {
    if (initialized.getAndSet(true)) {
        return;/* ww w. j a  v a2  s  .com*/
    }

    // HTTP parameters for the client
    final HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.connect.timeout", 30000));
    params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
            Integer.getInteger("com.googlecode.jsonrpc4j.async.socket.buffer", 8 * 1024));
    params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
            Boolean.valueOf(System.getProperty("com.googlecode.jsonrpc4j.async.tcp.nodelay", "true")));
    params.setParameter(CoreProtocolPNames.USER_AGENT, "jsonrpc4j/1.0");

    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor;
    try {
        IOReactorConfig config = new IOReactorConfig();
        config.setIoThreadCount(Integer.getInteger("com.googlecode.jsonrpc4j.async.reactor.threads", 1));
        ioReactor = new DefaultConnectingIOReactor(config);
    } catch (IOReactorException e) {
        throw new RuntimeException("Exception initializing asynchronous Apache HTTP Client", e);
    }

    // Create a default SSLSetupHandler that accepts any certificate
    if (sslContext == null) {
        try {
            sslContext = SSLContext.getDefault();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Create HTTP connection pool
    BasicNIOConnFactory nioConnFactory = new BasicNIOConnFactory(sslContext, null, params);
    pool = new BasicNIOConnPool(ioReactor, nioConnFactory, params);
    // Limit total number of connections to 500 by default
    pool.setDefaultMaxPerRoute(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.route", 500));
    pool.setMaxTotal(Integer.getInteger("com.googlecode.jsonrpc4j.async.max.inflight.total", 500));

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                // Create client-side HTTP protocol handler
                HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
                // Create client-side I/O event dispatch
                IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, sslContext,
                        params);
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
        }

    }, "jsonrpc4j HTTP IOReactor");
    // Start the client thread
    t.setDaemon(true);
    t.start();

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });

    // Create HTTP requester
    requester = new HttpAsyncRequester(httpproc, new DefaultConnectionReuseStrategy(), params);
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Makes a Http operation.//from   w  w w  .ja  v a2s.  c o m
 * 
 * This method set a parameters to the request that avoid being waiting 
 * for the server response or once connected, being waiting to receive 
 * the data.
 * 
 * @param method      Method type to execute. @See HTTP_METHOD.
 * @param url         Url of the request.
 * @param jsonData      The body content of the request (JSON). Can be null.
 * @param headers      The headers to include in the request.
 * @return The content of the request if there is one.
 * @throws Exception
 */
public static String net_httpclient_doAction(HTTP_METHOD method, String url, String jsonData,
        Map<String, String> headers) throws ConnectTimeoutException, SocketTimeoutException, Exception {
    String responseData = null;

    DefaultHttpClient httpclient = new DefaultHttpClient();

    // The time it takes to open TCP connection.
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_DEFAULT_TIMEOUT);
    // Timeout when server does not send data.
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
            CONNECTION_DEFAULT_DATA_RECEIVAL_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);

    HttpRequestBase httpMethod = null;
    switch (method) {
    case POST:
        httpMethod = new HttpPost(url);
        //Add the body to the request.
        StringEntity se = new StringEntity(jsonData);
        ((HttpPost) httpMethod).setEntity(se);
        break;
    case DELETE:
        httpMethod = new HttpDelete(url);
        break;
    case GET:
        httpMethod = new HttpGet(url);
        break;
    }

    //Add the headers to the request.
    if (headers != null) {
        for (String header : headers.keySet()) {
            httpMethod.setHeader(header, headers.get(header));
        }
    }

    HttpResponse response = httpclient.execute(httpMethod);
    if (LOG_ENABLE) {
        Log.d(TAG,
                "HTTP OPERATION: Read from server - Status Code: " + response.getStatusLine().getStatusCode());
        Log.d(TAG, "HTTP OPERATION: Read from server - Status Message: "
                + response.getStatusLine().getReasonPhrase());
    }

    //Get the response body if there is one.
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //responseData = EntityUtils.toString(entity, "UTF-8");

        InputStream instream = entity.getContent();
        responseData = IOUtils.convertStreamToString(instream);

        if (LOG_ENABLE)
            Log.i(TAG, "HTTP OPERATION: Read from server - return: " + responseData);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new Exception("Http operation " + method.name() + " failed with error code "
                + response.getStatusLine().getStatusCode() + "(" + response.getStatusLine().getReasonPhrase()
                + ")");
    }

    return responseData;
}