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

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

Introduction

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

Prototype

public HttpParams setParameter(String str, Object obj) 

Source Link

Usage

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private void addParams(HttpRequestBase request, Map<String, String> params)
        throws UnsupportedEncodingException {
    if (params != null && !params.isEmpty()) {
        BasicHttpParams prms = new BasicHttpParams();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            prms.setParameter(entry.getKey(), entry.getValue());
        }/*from   ww  w .  j  ava 2 s. c o  m*/
        request.setParams(prms);
    }
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private void addParams(HttpEntityEnclosingRequestBase request, Map<String, String> params)
        throws UnsupportedEncodingException {
    if (params != null && !params.isEmpty()) {
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        BasicHttpParams prms = new BasicHttpParams();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            prms.setParameter(entry.getKey(), entry.getValue());
        }/*w ww .java  2  s .co m*/
        request.setEntity(new UrlEncodedFormEntity(postParams, "UTF-8"));
        request.setParams(prms);
    }
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Initialize the HTTP client//from www . j a  v  a2s. c  o m
 * 
 * @param connections
 *            the maximum number of HTTP connections
 * @param socketBufferSize
 *            the socket buffer size
 * @param socketTimeout
 *            the socket buffer timeout
 */
private void init(int maxConnections, int socketBufferSize, int socketTimeout) throws Throwable {
    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // Oh, I am easy!
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain != null) {
                for (int i = 0; i < chain.length; i++) {
                    chain[i].checkValidity();
                }
            }
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

    };

    SSLContext sslcontext = SSLContext.getInstance("SSL");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    BasicHttpParams params = new BasicHttpParams();
    params.setParameter("http.protocol.handle-redirects", false);
    params.setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, socketBufferSize);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);

    // enable parallelism
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(maxConnections);
    ConnManagerParams.setMaxTotalConnections(params, maxConnections >= 2 ? maxConnections : 2);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    Scheme sch = new Scheme("https", sf, 443);
    schemeRegistry.register(sch);
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

    httpclient = new DefaultHttpClient(cm, params);
    BasicCookieStore cookieStore = new BasicCookieStore();
    httpclient.setCookieStore(cookieStore);
}

From source file:API.amazon.mws.orders.MarketplaceWebServiceOrdersClient.java

/**
 * Configure HttpClient with set of defaults as well as configuration from
 * MarketplaceWebServiceProductsConfig instance
 * /*from   w w w  .j a va 2  s.co  m*/
 */
private HttpClient configureHttpClient(String applicationName, String applicationVersion) {

    // respect a user-provided User-Agent header as-is, but if none is provided
    // then generate one satisfying the MWS User-Agent requirements
    if (config.getUserAgent() == null) {
        config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion),
                quoteAttributeValue("Java/" + System.getProperty("java.version") + "/"
                        + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")),

                quoteAttributeName("Platform"),
                quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch")
                        + "/" + System.getProperty("os.version")),

                quoteAttributeName("MWSClientVersion"), quoteAttributeValue(clientVersion));
    }

    defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent()));

    /* Set http client parameters */
    BasicHttpParams httpParams = new BasicHttpParams();

    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent());

    /* Set connection parameters */
    HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
    HttpConnectionParams.setSoTimeout(httpParams, 50000);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    /* Set connection manager */
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());

    /* Set http client */
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();

    /* Set proxy if configured */
    if (config.isSetProxyHost() && config.isSetProxyPort()) {
        log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + "Proxy Port: "
                + config.getProxyPort());
        final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(),
                (usesHttps(config.getServiceURL()) ? "https" : "http"));
        httpContext = new BasicHttpContext();
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);

        }

    }

    return httpClient;
}

From source file:com.amazonservices.mws.client.MwsConnection.java

/**
 * Initialize the connection.//ww w .java2 s . c o m
 */
synchronized void freeze() {
    if (frozen) {
        return;
    }
    if (userAgent == null) {
        setDefaultUserAgent();
    }
    serviceMap = new HashMap<String, ServiceEndpoint>();
    if (log.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Creating MwsConnection {");
        buf.append("applicationName:");
        buf.append(applicationName);
        buf.append(",applicationVersion:");
        buf.append(applicationVersion);
        buf.append(",awsAccessKeyId:");
        buf.append(awsAccessKeyId);
        buf.append(",uri:");
        buf.append(endpoint.toString());
        buf.append(",userAgent:");
        buf.append(userAgent);
        buf.append(",connectionTimeout:");
        buf.append(connectionTimeout);
        if (proxyHost != null && proxyPort != 0) {
            buf.append(",proxyUsername:");
            buf.append(proxyUsername);
            buf.append(",proxyHost:");
            buf.append(proxyHost);
            buf.append(",proxyPort:");
            buf.append(proxyPort);
        }
        buf.append("}");
        log.debug(buf);
    }

    BasicHttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
    HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    connectionManager = getConnectionManager();
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();
    if (proxyHost != null && proxyPort != 0) {
        String scheme = MwsUtl.usesHttps(endpoint) ? "https" : "http";
        HttpHost hostConfiguration = new HttpHost(proxyHost, proxyPort, scheme);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (proxyUsername != null && proxyPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
            CredentialsProvider cprovider = new BasicCredentialsProvider();
            cprovider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, cprovider);
        }
    }
    headers = Collections.unmodifiableMap(headers);
    frozen = true;
}

From source file:API.amazon.mws.products.MarketplaceWebServiceProductsClient.java

/**
 * Configure HttpClient with set of defaults as well as configuration from
 * MarketplaceWebServiceProductsConfig instance
 * /*from w ww  .  j  a  v  a 2  s  .  c  om*/
 */

private HttpClient configureHttpClient(String applicationName, String applicationVersion) {

    // respect a user-provided User-Agent header as-is, but if none is provided
    // then generate one satisfying the MWS User-Agent requirements
    if (config.getUserAgent() == null) {
        config.setUserAgent(quoteAppName(applicationName), quoteAppVersion(applicationVersion),
                quoteAttributeValue("Java/" + System.getProperty("java.version") + "/"
                        + System.getProperty("java.class.version") + "/" + System.getProperty("java.vendor")),

                quoteAttributeName("Platform"),
                quoteAttributeValue("" + System.getProperty("os.name") + "/" + System.getProperty("os.arch")
                        + "/" + System.getProperty("os.version")),

                quoteAttributeName("MWSClientVersion"), quoteAttributeValue(clientVersion));
    }

    defaultHeaders.add(new BasicHeader("X-Amazon-User-Agent", config.getUserAgent()));

    /* Set http client parameters */
    BasicHttpParams httpParams = new BasicHttpParams();

    httpParams.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgent());

    /* Set connection parameters */
    HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
    HttpConnectionParams.setSoTimeout(httpParams, 50000);
    HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);

    /* Set connection manager */
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());

    /* Set http client */
    httpClient = new DefaultHttpClient(connectionManager, httpParams);
    httpContext = new BasicHttpContext();

    /* Set proxy if configured */
    if (config.isSetProxyHost() && config.isSetProxyPort()) {
        log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() + "Proxy Port: "
                + config.getProxyPort());
        final HttpHost hostConfiguration = new HttpHost(config.getProxyHost(), config.getProxyPort(),
                (usesHttps(config.getServiceURL()) ? "https" : "http"));
        httpContext = new BasicHttpContext();
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

        if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);

        }

    }

    return httpClient;
}

From source file:cn.com.zzwfang.http.HttpClient.java

/**
 * Cookie//ww w  .  j  a v  a2 s .c  om
 */
//   private PersistentCookieStore cookieStore;

public HttpClient(Context context) {
    if (httpClient != null) {
        return;
    }
    //      Log.i("--->", "HttpClient ?httpClient-------------");
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, totalConnections);

    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, userAgent);

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

    httpParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.setHttpRequestRetryHandler(new InnerRetryHandler(DEFAULT_MAX_RETRIES));
    //      cookieStore = new PersistentCookieStore(context);
    //      httpContext.setAttribute("http.cookie-store", cookieStore);
    //      httpClient.setCookieStore(cookieStore);

}

From source file:org.wso2.carbon.analytics.api.internal.client.AnalyticsAPIHttpClient.java

private AnalyticsAPIHttpClient(String protocol, String hostname, int port, int maxPerRoute, int maxConnection,
        int socketTimeout, int connectionTimeout, String trustStoreLocation, String trustStorePassword) {
    this.hostname = hostname;
    this.port = port;
    this.protocol = protocol;
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (this.protocol.equalsIgnoreCase(AnalyticsDataConstants.HTTP_PROTOCOL)) {
        schemeRegistry.register(new Scheme(this.protocol, port, PlainSocketFactory.getSocketFactory()));
    } else {/*from w  w  w . j  a va 2s. c  o  m*/
        System.setProperty(AnalyticsDataConstants.SSL_TRUST_STORE_SYS_PROP, trustStoreLocation);
        System.setProperty(AnalyticsDataConstants.SSL_TRUST_STORE_PASSWORD_SYS_PROP, trustStorePassword);
        schemeRegistry.register(new Scheme(this.protocol, port, SSLSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setDefaultMaxPerRoute(maxPerRoute);
    connectionManager.setMaxTotal(maxConnection);
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(AllClientPNames.SO_TIMEOUT, socketTimeout);
    params.setParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout);
    this.httpClient = new DefaultHttpClient(connectionManager, params);
    gson = new GsonBuilder().create();
}

From source file:org.dataconservancy.access.connector.HttpDcsConnector.java

public HttpDcsConnector(DcsConnectorConfig config, DcsModelBuilder mb) {
    if (config == null) {
        throw new IllegalArgumentException("DcsConnectorConfig must not be null.");
    }// w  ww  .j a  va 2  s  .c  o  m

    if (mb == null) {
        throw new IllegalArgumentException("DcsModelBuilder must not be null.");
    }

    this.config = config;
    this.mb = mb;

    final ClientConnectionManager cm;
    final BasicHttpParams httpParams = new BasicHttpParams();

    if (config.getMaxOpenConn() > 1) {
        final SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        ConnManagerParams.setMaxTotalConnections(httpParams, config.getMaxOpenConn());
        ConnPerRouteBean connPerRoute = new ConnPerRouteBean(config.getMaxOpenConn());
        ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
        if (config.getConnPoolTimeout() > 0) {
            ConnManagerParams.setTimeout(httpParams, config.getConnPoolTimeout() * 1000);
        }
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
        new ConnectionMonitorThread(cm).start();
    } else {
        cm = null;
    }

    if (config.getConnTimeout() > 0) {
        httpParams.setParameter("http.connection.timeout", config.getConnTimeout() * 1000);
        httpParams.setParameter("http.socket.timeout", config.getConnTimeout() * 1000);
    }

    this.client = new DefaultHttpClient(cm, httpParams);
    log.debug("Instantiated {} ({}) with configuration {}",
            new Object[] { this.getClass().getName(), System.identityHashCode(this), config });
}