Example usage for org.apache.http.params BasicHttpParams BasicHttpParams

List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams

Introduction

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

Prototype

public BasicHttpParams() 

Source Link

Usage

From source file:com.yanzhenjie.andserver.DefaultAndServer.java

@Override
public void run() {
    try {//www.  ja va 2 s  . c o  m
        mServerSocket = new ServerSocket();
        mServerSocket.setReuseAddress(true);
        mServerSocket.bind(new InetSocketAddress(mPort));

        // HTTP??
        BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
        httpProcessor.addInterceptor(new ResponseDate());
        httpProcessor.addInterceptor(new ResponseServer());
        httpProcessor.addInterceptor(new ResponseContent());
        httpProcessor.addInterceptor(new ResponseConnControl());

        // HTTP Attribute.
        HttpParams httpParams = new BasicHttpParams();
        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout)
                .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
                .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
                .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
                .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "WebServer/1.1");

        // Http?
        HttpRequestHandlerRegistry handlerRegistry = new HttpRequestHandlerRegistry();
        for (Map.Entry<String, AndServerRequestHandler> handlerEntry : mRequestHandlerMap.entrySet()) {
            handlerRegistry.register("/" + handlerEntry.getKey(),
                    new DefaultHttpRequestHandler(handlerEntry.getValue()));
        }

        // HTTP?
        HttpService httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(),
                new DefaultHttpResponseFactory());
        httpService.setParams(httpParams);
        httpService.setHandlerResolver(handlerRegistry);

        /**
         * ?
         */
        while (isLoop) {
            // 
            if (!mServerSocket.isClosed()) {
                Socket socket = mServerSocket.accept();
                DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection();
                serverConnection.bind(socket, httpParams);

                // Dispatch request handler.
                RequestHandleTask requestTask = new RequestHandleTask(this, httpService, serverConnection);
                requestTask.setDaemon(true);
                AndWebUtil.executeRunnable(requestTask);
            }
        }
    } catch (Exception e) {
    } finally {
        close();
    }
}

From source file:com.quantcast.measurement.service.QCDataUploader.java

String synchronousUploadEvents(Collection<QCEvent> events) {
    if (events == null || events.isEmpty())
        return null;

    String uploadId = QCUtility.generateUniqueId();

    JSONObject upload = new JSONObject();
    try {//  www . j  a  v  a  2s. c o  m
        upload.put(QC_UPLOAD_ID_KEY, uploadId);
        upload.put(QC_QCV_KEY, QCUtility.API_VERSION);
        upload.put(QCEvent.QC_APIKEY_KEY, QCMeasurement.INSTANCE.getApiKey());
        upload.put(QCEvent.QC_NETWORKCODE_KEY, QCMeasurement.INSTANCE.getNetworkCode());
        upload.put(QCEvent.QC_DEVICEID_KEY, QCMeasurement.INSTANCE.getDeviceId());

        JSONArray event = new JSONArray();
        for (QCEvent e : events) {
            event.put(new JSONObject(e.getParameters()));
        }
        upload.put(QC_EVENTS_KEY, event);
    } catch (JSONException e) {
        QCLog.e(TAG, "Error while encoding json.");
        return null;
    }

    int code;
    String url = QCUtility.addScheme(UPLOAD_URL_WITHOUT_SCHEME);
    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    defaultHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
    final BasicHttpContext localContext = new BasicHttpContext();

    try {
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(upload.toString(), HTTP.UTF_8);
        post.setEntity(se);

        HttpParams params = new BasicHttpParams();
        params.setBooleanParameter("http.protocol.expect-continue", false);
        post.setParams(params);

        HttpResponse response = defaultHttpClient.execute(post, localContext);
        code = response.getStatusLine().getStatusCode();
    } catch (Exception e) {
        QCLog.e(TAG, "Could not upload events", e);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure", e.toString(), null);
        code = HttpStatus.SC_REQUEST_TIMEOUT;
    }

    if (!isSuccessful(code)) {
        uploadId = null;
        QCLog.e(TAG, "Events not sent to server. Response code: " + code);
        QCMeasurement.INSTANCE.logSDKError("json-upload-failure",
                "Bad response from server. Response code: " + code, null);
    }
    return uploadId;
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }/*  ww w .j  a  v  a  2s.  c  om*/
    }) {
        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host,
                InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context)
                throws IOException {
            if (socket instanceof SSLSocket) {
                try {
                    PropertyUtils.setProperty(socket, "host", host.getHostName());
                } catch (Exception ex) {
                    LOG.warn(String.format(
                            "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s",
                            ex.toString()));
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:org.thoughtcrime.securesms.mms.MmsCommunication.java

protected static HttpClient constructHttpClient(MmsConnectionParameters mmsConfig) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
    HttpConnectionParams.setSoTimeout(params, 20 * 1000);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    HttpClientParams.setRedirecting(params, false);
    HttpProtocolParams.setUserAgent(params, "TextSecure/0.1");
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    if (mmsConfig.hasProxy()) {
        ConnRouteParams.setDefaultProxy(params, new HttpHost(mmsConfig.getProxy(), mmsConfig.getPort()));
    }/*from w  w w.  j a  v a 2  s.  com*/

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

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);
    return new DefaultHttpClient(manager, params);
}

From source file:com.zotoh.maedr.device.apache.HttpIO.java

protected void onStart() throws Exception {

    // mostly copied from apache http tutotial...

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, (int) getSocetTimeoutMills())
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) // 8k?
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Apache-HttpCore/4.x");

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    ConnectionReuseStrategy strategy = new DefaultConnectionReuseStrategy();
    HttpResponseFactory rspFac = new DefaultHttpResponseFactory();
    NHttpServiceHandler svc;/*  w  ww  .j  ava2  s  . c  om*/
    EventListener evt = new EventLogger(getId(), tlog());

    if (isAsync()) {
        AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler(httpproc, rspFac, strategy, params);
        NHttpRequestHandlerRegistry r = new NHttpRequestHandlerRegistry();
        r.register("*", new HttpNRequestCB(this));
        handler.setHandlerResolver(r);
        handler.setEventListener(evt);
        svc = handler;
    } else {
        StreamedHttpServiceHandler handler = new StreamedHttpServiceHandler(httpproc, rspFac, strategy, params);
        HttpRequestHandlerRegistry r = new HttpRequestHandlerRegistry();
        r.register("*", new HttpRequestCB(this));
        handler.setHandlerResolver(r);
        handler.setEventListener(evt);
        svc = handler;
    }

    IOEventDispatch disp = isSSL() ? onSSL(svc, params) : onBasic(svc, params);
    ListeningIOReactor ioReactor;
    ioReactor = new DefaultListeningIOReactor(getWorkers(), params);
    ioReactor.listen(new InetSocketAddress(NetUte.getNetAddr(getHost()), getPort()));
    _curIO = ioReactor;

    // start...
    runServer(disp, ioReactor);
}

From source file:org.nuxeo.scim.server.tests.ScimServerTest.java

protected static ClientConfig createHttpBasicClientConfig(final String userName, final String password) {

    final HttpParams params = new BasicHttpParams();
    DefaultHttpClient.setDefaultHttpParams(params);
    params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, true);
    params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
    params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);

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

    final PoolingClientConnectionManager mgr = new PoolingClientConnectionManager(schemeRegistry);
    mgr.setMaxTotal(200);/*  ww  w  . j a v a 2s  .c  om*/
    mgr.setDefaultMaxPerRoute(20);

    final DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);

    final Credentials credentials = new UsernamePasswordCredentials(userName, password);
    httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
    httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);

    ClientConfig clientConfig = new ApacheHttpClientConfig(httpClient);
    clientConfig.setBypassHostnameVerification(true);

    return clientConfig;
}

From source file:pt.lunacloud.http.HttpClientFactory.java

/**
 * Creates a new HttpClient object using the specified AWS
 * ClientConfiguration to configure the client.
 *
 * @param config/*from  w ww. j  a  v a 2 s .  c o m*/
 *            Client configuration options (ex: proxy settings, connection
 *            limits, etc).
 *
 * @return The new, configured HttpClient.
 */
public HttpClient createHttpClient(ClientConfiguration config) {
    /* Form User-Agent information */
    String userAgent = config.getUserAgent();
    if (!(userAgent.equals(ClientConfiguration.DEFAULT_USER_AGENT))) {
        userAgent += ", " + ClientConfiguration.DEFAULT_USER_AGENT;
    }

    /* Set HTTP client parameters */
    HttpParams httpClientParams = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(httpClientParams, userAgent);
    HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, false);
    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 LunacloudClientException("Unable to access default SSL context");
    }

    /*
     * 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.android.idtt.HttpUtils.java

public HttpUtils(int connTimeout) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

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

    httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override//from   w w  w.  j a  v  a  2  s . c o  m
        public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
                httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext httpContext)
                throws org.apache.http.HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }
    });
}

From source file:monasca.common.middleware.HttpClientPoolFactory.java

HttpClientPoolFactory(String host, int port, boolean useHttps, int timeout, boolean clientAuth, String keyStore,
        String keyPass, String trustStore, String trustPass, String adminToken, int maxActive,
        long timeBetweenEvictionRunsMillis, long minEvictableIdleTimeMillis) {
    // Setup auth URL
    String protocol = useHttps ? "https://" : "http://";
    String urlStr = protocol + host + ":" + port;
    uri = URI.create(urlStr);// w  w  w.jav a  2  s . co  m

    // Setup connection pool
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (protocol.startsWith("https")) {
        SSLSocketFactory sslf = sslFactory(keyStore, keyPass, trustStore, trustPass, clientAuth);
        schemeRegistry.register(new Scheme("https", port, sslf));
    } else {
        schemeRegistry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
    }
    connMgr = new PoolingClientConnectionManager(schemeRegistry, minEvictableIdleTimeMillis,
            TimeUnit.MILLISECONDS);

    connMgr.setMaxTotal(maxActive);
    connMgr.setDefaultMaxPerRoute(maxActive);

    // Http connection timeout
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

    // Create a single client
    client = new DefaultHttpClient(connMgr, params);

    // Create and start the connection pool cleaner
    cleaner = new HttpPoolCleaner(connMgr, timeBetweenEvictionRunsMillis, minEvictableIdleTimeMillis);
    new Thread(cleaner).start();

}

From source file:com.autonomousturk.crawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

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

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }// w w  w .j  ava2s  . c o  m

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

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

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}