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

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

Introduction

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

Prototype

HttpParams setParameter(String str, Object obj);

Source Link

Usage

From source file:org.apache.http.benchmark.HttpBenchmark.java

private HttpParams getHttpParams(int socketTimeout, boolean useHttp1_0, boolean useExpectContinue) {

    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpProtocolParams.PROTOCOL_VERSION,
            useHttp1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1)
            .setParameter(HttpProtocolParams.USER_AGENT, "HttpCore-AB/1.1")
            .setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, useExpectContinue)
            .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false)
            .setIntParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeout);
    return params;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

private HttpClient setupClient(URL url, SampleResult res) {

    Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY
            .get();/* w  ww. j  ava2 s  .c o m*/

    final String host = url.getHost();
    String proxyHost = getProxyHost();
    int proxyPort = getProxyPortInt();
    String proxyPass = getProxyPass();
    String proxyUser = getProxyUser();

    // static proxy is the globally define proxy eg command line or properties
    boolean useStaticProxy = isStaticProxy(host);
    // dynamic proxy is the proxy defined for this sampler
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);
    boolean useProxy = useStaticProxy || useDynamicProxy;

    // if both dynamic and static are used, the dynamic proxy has priority over static
    if (!useDynamicProxy) {
        proxyHost = PROXY_HOST;
        proxyPort = PROXY_PORT;
        proxyUser = PROXY_USER;
        proxyPass = PROXY_PASS;
    }

    // Lookup key - must agree with all the values used to create the HttpClient.
    HttpClientKey key = new HttpClientKey(url, useProxy, proxyHost, proxyPort, proxyUser, proxyPass);

    HttpClient httpClient = null;
    if (this.testElement.isConcurrentDwn()) {
        httpClient = (HttpClient) JMeterContextService.getContext().getSamplerContext().get(HTTPCLIENT_TOKEN);
    }

    if (httpClient == null) {
        httpClient = mapHttpClientPerHttpClientKey.get(key);
    }

    if (httpClient != null && resetSSLContext
            && HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(url.getProtocol())) {
        ((AbstractHttpClient) httpClient).clearRequestInterceptors();
        ((AbstractHttpClient) httpClient).clearResponseInterceptors();
        httpClient.getConnectionManager().closeIdleConnections(1L, TimeUnit.MICROSECONDS);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) { // One-time init for this client

        HttpParams clientParams = new DefaultedHttpParams(new BasicHttpParams(), DEFAULT_HTTP_PARAMS);

        DnsResolver resolver = this.testElement.getDNSResolver();
        if (resolver == null) {
            resolver = SystemDefaultDnsResolver.INSTANCE;
        }
        MeasuringConnectionManager connManager = new MeasuringConnectionManager(createSchemeRegistry(),
                resolver, TIME_TO_LIVE, VALIDITY_AFTER_INACTIVITY_TIMEOUT);

        // Modern browsers use more connections per host than the current httpclient default (2)
        // when using parallel download the httpclient and connection manager are shared by the downloads threads
        // to be realistic JMeter must set an higher value to DefaultMaxPerRoute
        if (this.testElement.isConcurrentDwn()) {
            try {
                int maxConcurrentDownloads = Integer.parseInt(this.testElement.getConcurrentPool());
                connManager.setDefaultMaxPerRoute(
                        Math.max(maxConcurrentDownloads, connManager.getDefaultMaxPerRoute()));
            } catch (NumberFormatException nfe) {
                // no need to log -> will be done by the sampler
            }
        }

        httpClient = new DefaultHttpClient(connManager, clientParams) {
            @Override
            protected HttpRequestRetryHandler createHttpRequestRetryHandler() {
                return new DefaultHttpRequestRetryHandler(RETRY_COUNT, false); // set retry count
            }
        };

        if (IDLE_TIMEOUT > 0) {
            ((AbstractHttpClient) httpClient).setKeepAliveStrategy(IDLE_STRATEGY);
        }
        // see https://issues.apache.org/jira/browse/HTTPCORE-397
        ((AbstractHttpClient) httpClient).setReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE);
        ((AbstractHttpClient) httpClient).addResponseInterceptor(RESPONSE_CONTENT_ENCODING);
        ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK
        ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER);

        // Override the default schemes as necessary
        SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();

        if (SLOW_HTTP != null) {
            schemeRegistry.register(SLOW_HTTP);
        }

        // Set up proxy details
        if (useProxy) {

            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (proxyUser.length() > 0) {
                ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
                        new AuthScope(proxyHost, proxyPort),
                        new NTCredentials(proxyUser, proxyPass, localHost, PROXY_DOMAIN));
            }
        }

        // Bug 52126 - we do our own cookie handling
        clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookieSpecs.IGNORE_COOKIES);

        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }

        mapHttpClientPerHttpClientKey.put(key, httpClient); // save the agent for next time round
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient) + " " + key.toString());
        }
    }

    if (this.testElement.isConcurrentDwn()) {
        JMeterContextService.getContext().getSamplerContext().put(HTTPCLIENT_TOKEN, httpClient);
    }

    // TODO - should this be done when the client is created?
    // If so, then the details need to be added as part of HttpClientKey
    setConnectionAuthorization(httpClient, url, getAuthManager(), key);

    return httpClient;
}

From source file:org.dasein.cloud.aws.AWSCloud.java

public @Nonnull HttpClient getClient(boolean multipart) throws InternalException {
    ProviderContext ctx = getContext();//from w  w  w  .j  av  a  2  s . c  om
    if (ctx == null) {
        throw new InternalException("No context was specified for this request");
    }

    final HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    if (!multipart) {
        HttpProtocolParams.setContentCharset(params, Consts.UTF_8.toString());
    }
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

    Properties p = ctx.getCustomProperties();
    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPortStr = p.getProperty("proxyPort");
        int proxyPort = 0;
        if (proxyPortStr != null) {
            proxyPort = Integer.parseInt(proxyPortStr);
        }
        if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
        }
    }
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
            request.setParams(params);
        }
    });
    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header header = entity.getContentEncoding();
                if (header != null) {
                    for (HeaderElement codec : header.getElements()) {
                        if (codec.getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }
        }
    });
    return httpClient;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

protected @Nonnull HttpClient getClient() throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was defined for this request");
    }/*  w  w  w  .j  a v  a  2s . c om*/
    String endpoint = getStorageEnpoint();
    boolean ssl = endpoint.startsWith("https");
    int targetPort;

    try {

        URI uri = new URI(endpoint);
        targetPort = uri.getPort();

        if (targetPort < 1) {
            targetPort = (ssl ? 443 : 80);
        }
    } catch (URISyntaxException e) {
        throw new AzureConfigException(e);
    }
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);

}

From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException("No context was defined for this request");
    }/*  w ww .ja  v a2s  .c  o m*/
    String endpoint = ctx.getCloud().getEndpoint();

    if (endpoint == null) {
        throw new InternalException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");

    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    DefaultHttpClient client = new DefaultHttpClient(params);

    if (provider.isInsecure()) {
        try {
            client.getConnectionManager().getSchemeRegistry()
                    .register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() {

                        public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                                throws CertificateException {
                            return true;
                        }
                    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
    return client;
}

From source file:org.dasein.cloud.virtustream.VirtustreamMethod.java

private @Nonnull HttpClient getClient(URI uri) throws InternalException, CloudException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new InternalException();
    }/*from ww w  .j  a va 2  s.c  om*/
    boolean ssl = uri.getScheme().startsWith("https");
    HttpParams params = new BasicHttpParams();

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    //noinspection deprecation
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "");

    Properties p = ctx.getCustomProperties();

    if (p != null) {
        String proxyHost = p.getProperty("proxyHost");
        String proxyPort = p.getProperty("proxyPort");

        if (proxyHost != null) {
            int port = 0;

            if (proxyPort != null && proxyPort.length() > 0) {
                port = Integer.parseInt(proxyPort);
            }
            params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                    new HttpHost(proxyHost, port, ssl ? "https" : "http"));
        }
    }
    return new DefaultHttpClient(params);
}

From source file:org.kochka.android.weightlogger.tools.GarminConnect.java

public boolean signin(final String username, final String password) {
    httpclient = new DefaultHttpClient();
    final String signin_url = "https://sso.garmin.com/sso/login?service=http://connect.garmin.com/post-auth/login&clientId=GarminConnect&consumeServiceTicket=false";
    final String auth_url = "http://connect.garmin.com/post-auth/login";

    try {// w w  w.  jav a2 s  . c  om
        HttpEntity entity;
        Pattern r;
        Matcher m;

        HttpParams params = new BasicHttpParams();
        params.setParameter("http.protocol.handle-redirects", false);

        // Create session
        entity = httpclient.execute(new HttpGet(signin_url)).getEntity();
        r = Pattern.compile("name=\"lt\"\\s+value=\"([^\"]+)\"");
        m = r.matcher(EntityUtils.toString(entity));
        m.find();
        String lt_param = m.group(1);

        // Sign in
        HttpPost post = new HttpPost(signin_url);
        post.setParams(params);
        List<NameValuePair> nvp = new ArrayList<NameValuePair>();
        nvp.add(new BasicNameValuePair("_eventId", "submit"));
        nvp.add(new BasicNameValuePair("displayNameRequired", "false"));
        nvp.add(new BasicNameValuePair("embed", "true"));
        nvp.add(new BasicNameValuePair("lt", lt_param));
        nvp.add(new BasicNameValuePair("username", username));
        nvp.add(new BasicNameValuePair("password", password));
        post.setEntity(new UrlEncodedFormEntity(nvp));
        entity = httpclient.execute(post).getEntity();
        r = Pattern.compile("ticket=([^']+)'");
        m = r.matcher(EntityUtils.toString(entity));
        m.find();
        String ticket = m.group(1);

        // Ticket
        HttpGet get = new HttpGet(auth_url + "?ticket=" + ticket);
        get.setParams(params);
        httpclient.execute(get).getEntity().consumeContent();

        return isSignedIn();
    } catch (Exception e) {
        httpclient.getConnectionManager().shutdown();
        return false;
    }
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

@Override
public void init() throws ServletException {
    String doLogStr = getConfigParam(P_LOG);
    if (doLogStr != null) {
        this.doLog = Boolean.parseBoolean(doLogStr);
    }/*w  w w.  j  a v a  2s .co m*/

    String doForwardIPString = getConfigParam(P_FORWARDEDFOR);
    if (doForwardIPString != null) {
        this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
    }

    initTarget();// sets target*

    HttpParams hcParams = new BasicHttpParams();
    hcParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
    hcParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); // See
    // #70
    readConfigParam(hcParams, ClientPNames.HANDLE_REDIRECTS, Boolean.class);
    proxyClient = createHttpClient(hcParams);
}

From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java

/**
 * Reads a servlet config parameter by the name {@code hcParamName} of type
 * {@code type}, and set it in {@code hcParams}.
 *//*from  w ww. j a v a 2 s. com*/
protected void readConfigParam(HttpParams hcParams, String hcParamName, Class<?> type) {
    String val_str = getConfigParam(hcParamName);
    if (val_str == null)
        return;
    Object val_obj;
    if (type == String.class) {
        val_obj = val_str;
    } else {
        try {
            // noinspection unchecked
            val_obj = type.getMethod("valueOf", String.class).invoke(type, val_str);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    hcParams.setParameter(hcParamName, val_obj);
}