List of usage examples for org.apache.http.params HttpParams setParameter
HttpParams setParameter(String str, Object obj);
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
private HttpClient setupClient(URL url, SampleResult res) { Map<HttpClientKey, HttpClient> mapHttpClientPerHttpClientKey = HTTPCLIENTS_CACHE_PER_THREAD_AND_HTTPCLIENTKEY .get();// ww w.jav a 2 s. com final String host = url.getHost(); final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); boolean useStaticProxy = isStaticProxy(host); boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort); // Lookup key - must agree with all the values used to create the HttpClient. HttpClientKey key = new HttpClientKey(url, (useStaticProxy || useDynamicProxy), useDynamicProxy ? proxyHost : PROXY_HOST, useDynamicProxy ? proxyPort : PROXY_PORT, useDynamicProxy ? getProxyUser() : PROXY_USER, useDynamicProxy ? getProxyPass() : PROXY_PASS); HttpClient 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 = new SystemDefaultDnsResolver(); } ClientConnectionManager connManager = new MeasuringConnectionManager( SchemeRegistryFactory.createDefault(), resolver); 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); } ((AbstractHttpClient) httpClient).addResponseInterceptor(new ResponseContentEncoding()); ((AbstractHttpClient) httpClient).addResponseInterceptor(METRICS_SAVER); // HACK ((AbstractHttpClient) httpClient).addRequestInterceptor(METRICS_RESETTER); // Override the defualt schemes as necessary SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); if (SLOW_HTTP != null) { schemeRegistry.register(SLOW_HTTP); } if (HTTPS_SCHEME != null) { schemeRegistry.register(HTTPS_SCHEME); } // Set up proxy details if (useDynamicProxy) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); String proxyUser = getProxyUser(); if (proxyUser.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUser, getProxyPass(), localHost, PROXY_DOMAIN)); } } else if (useStaticProxy) { HttpHost proxy = new HttpHost(PROXY_HOST, PROXY_PORT); clientParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (PROXY_USER.length() > 0) { ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials( new AuthScope(PROXY_HOST, PROXY_PORT), new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN)); } } // Bug 52126 - we do our own cookie handling clientParams.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.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()); } } MeasuringConnectionManager connectionManager = (MeasuringConnectionManager) httpClient .getConnectionManager(); connectionManager.setSample(res); // 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:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java
@Override protected @Nonnull HttpClient getClient() throws CloudException, InternalException { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new InternalException("No context was defined for this request"); }//from w w w . j a v a 2s .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() { @Override 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:com.marklogic.client.impl.JerseyServices.java
private void connect(String host, int port, String database, String user, String password, Authentication authenType, SSLContext context, X509HostnameVerifier verifier) { if (logger.isDebugEnabled()) logger.debug("Connecting to {} at {} as {}", new Object[] { host, port, user }); if (host == null) throw new IllegalArgumentException("No host provided"); if (authenType == null) { if (context != null) { authenType = Authentication.BASIC; }//from w w w . j av a 2s .co m } if (authenType != null) { if (user == null) throw new IllegalArgumentException("No user provided"); if (password == null) throw new IllegalArgumentException("No password provided"); } if (connection != null) connection = null; if (client != null) { client.destroy(); client = null; } this.database = database; String baseUri = ((context == null) ? "http" : "https") + "://" + host + ":" + port + "/v1/"; Properties props = System.getProperties(); if (props.containsKey(MAX_DELAY_PROP)) { String maxDelayStr = props.getProperty(MAX_DELAY_PROP); if (maxDelayStr != null && maxDelayStr.length() > 0) { int max = Integer.parseInt(maxDelayStr); if (max > 0) { maxDelay = max * 1000; } } } if (props.containsKey(MIN_RETRY_PROP)) { String minRetryStr = props.getProperty(MIN_RETRY_PROP); if (minRetryStr != null && minRetryStr.length() > 0) { int min = Integer.parseInt(minRetryStr); if (min > 0) { minRetry = min; } } } // TODO: integrated control of HTTP Client and Jersey Client logging if (!props.containsKey("org.apache.commons.logging.Log")) { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); } if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http")) { System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "warn"); } if (!props.containsKey("org.apache.commons.logging.simplelog.log.org.apache.http.wire")) { System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire", "warn"); } Scheme scheme = null; if (context == null) { SchemeSocketFactory socketFactory = PlainSocketFactory.getSocketFactory(); scheme = new Scheme("http", port, socketFactory); } else { SSLSocketFactory socketFactory = new SSLSocketFactory(context, verifier); scheme = new Scheme("https", port, socketFactory); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(scheme); int maxRouteConnections = 100; int maxTotalConnections = 2 * maxRouteConnections; /* * 4.2 PoolingClientConnectionManager connMgr = new * PoolingClientConnectionManager(schemeRegistry); * connMgr.setMaxTotal(maxTotalConnections); * connMgr.setDefaultMaxPerRoute(maxRouteConnections); * connMgr.setMaxPerRoute( new HttpRoute(new HttpHost(baseUri)), * maxRouteConnections); */ // start 4.1 ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(schemeRegistry); connMgr.setMaxTotal(maxTotalConnections); connMgr.setDefaultMaxPerRoute(maxRouteConnections); connMgr.setMaxForRoute(new HttpRoute(new HttpHost(baseUri)), maxRouteConnections); // end 4.1 // CredentialsProvider credentialsProvider = new // BasicCredentialsProvider(); // credentialsProvider.setCredentials(new AuthScope(host, port), // new UsernamePasswordCredentials(user, password)); HttpParams httpParams = new BasicHttpParams(); if (authenType != null) { List<String> authpref = new ArrayList<String>(); if (authenType == Authentication.BASIC) authpref.add(AuthPolicy.BASIC); else if (authenType == Authentication.DIGEST) authpref.add(AuthPolicy.DIGEST); else throw new MarkLogicInternalException( "Internal error - unknown authentication type: " + authenType.name()); httpParams.setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); } httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); // HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); // long-term alternative to isFirstRequest alive // HttpProtocolParams.setUseExpectContinue(httpParams, false); // httpParams.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 1000); DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); Map<String, Object> configProps = config.getProperties(); configProps.put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, false); configProps.put(ApacheHttpClient4Config.PROPERTY_DISABLE_COOKIES, true); configProps.put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, connMgr); // ignored? configProps.put(ApacheHttpClient4Config.PROPERTY_FOLLOW_REDIRECTS, false); // configProps.put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, // credentialsProvider); configProps.put(ApacheHttpClient4Config.PROPERTY_HTTP_PARAMS, httpParams); // switches from buffered to streamed in Jersey Client configProps.put(ApacheHttpClient4Config.PROPERTY_CHUNKED_ENCODING_SIZE, 32 * 1024); client = ApacheHttpClient4.create(config); // System.setProperty("javax.net.debug", "all"); // all or ssl if (authenType == null) { checkFirstRequest = false; } else if (authenType == Authentication.BASIC) { checkFirstRequest = false; client.addFilter(new HTTPBasicAuthFilter(user, password)); } else if (authenType == Authentication.DIGEST) { checkFirstRequest = true; // workaround for JerseyClient bug 1445 client.addFilter(new DigestChallengeFilter()); client.addFilter(new HTTPDigestAuthFilter(user, password)); } else { throw new MarkLogicInternalException( "Internal error - unknown authentication type: " + authenType.name()); } // client.addFilter(new LoggingFilter(System.err)); connection = client.resource(baseUri); }