List of usage examples for org.apache.http.params CoreConnectionPNames SO_TIMEOUT
String SO_TIMEOUT
To view the source code for org.apache.http.params CoreConnectionPNames SO_TIMEOUT.
Click Source Link
From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java
@PostConstruct protected void initialize() { try {//from www . j a v a2s .co m lock.writeLock().lock(); httpParams = new BasicHttpParams(); String userAgentString = "Apache Marmotta/" + configurationService.getStringConfiguration("kiwi.version") + " (running at " + configurationService.getServerUri() + ")" + " lmf-core/" + configurationService.getStringConfiguration("kiwi.version"); userAgentString = configurationService.getStringConfiguration("core.http.user_agent", userAgentString); httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, configurationService.getIntConfiguration("core.http.so_timeout", 60000)); httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, configurationService.getIntConfiguration("core.http.connection_timeout", 10000)); httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS, 20)); cm.setDefaultMaxPerRoute( configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS_PER_ROUTE, 10)); final DefaultHttpClient hc = new DefaultHttpClient(cm, httpParams); hc.setRedirectStrategy(new LMFRedirectStrategy()); hc.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler()); hc.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class); hc.addRequestInterceptor(new LMFRequestUserAgent(userAgentString)); if (configurationService.getBooleanConfiguration(CoreOptions.HTTP_CLIENT_CACHE_ENABLE, true)) { CacheConfig cacheConfig = new CacheConfig(); // FIXME: Hardcoded constants - is this useful? cacheConfig.setMaxCacheEntries(1000); cacheConfig.setMaxObjectSize(81920); final HttpCacheStorage cacheStore = new MapHttpCacheStorage(httpCache); this.httpClient = new MonitoredHttpClient(new CachingHttpClient(hc, cacheStore, cacheConfig)); } else { this.httpClient = new MonitoredHttpClient(hc); } bytesSent.set(0); bytesReceived.set(0); requestsExecuted.set(0); idleConnectionMonitorThread = new IdleConnectionMonitorThread(httpClient.getConnectionManager()); idleConnectionMonitorThread.start(); StatisticsProvider stats = new StatisticsProvider(cm); statisticsService.registerModule(HttpClientService.class.getSimpleName(), stats); } finally { lock.writeLock().unlock(); } }
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 www. j ava 2s . com 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:fr.natoine.html.HTMLPage.java
@SuppressWarnings("finally") public String extractFullContentResource(String _url, int _time_to_respond) { String response_content = null; HttpClient httpclient = new DefaultHttpClient(); //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET , "UTF-8"); //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16"); //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "ISO-8859-1"); //US-ASCII/*from ww w.ja v a 2 s . co m*/ //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "US-ASCII"); httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); httpclient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true); httpclient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); //HttpParams params = //HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet(_url); try { //Timer pour mettre un dlai sur le temps d'excution de la requte //Timer timer = new Timer(); //timer.schedule(new TimerTaskTooLong(httpget , _url) , _time_to_respond); //HttpResponse response = httpclient.execute(httpget); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); if (responseBody != null) { response_content = responseBody; // valid = true ; } } catch (ClientProtocolException e) { // valid = false ; System.out.println( "[HTMLPage.extractFullContentCssLink] url : " + _url + " doesn't support GET requests !!! "); e.printStackTrace(); } catch (IOException e) { // valid = false ; System.out.println( "[HTMLPage.extractFullContentCssLink] url : " + _url + " send no data !!! Not responding ... "); e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); return response_content; } }
From source file:org.graphity.core.util.jena.HttpQuery.java
private InputStream execPost() throws QueryExceptionHTTP { URL target = null;/*from ww w . ja va 2 s.co m*/ try { target = new URL(serviceURL); } catch (MalformedURLException malEx) { throw new QueryExceptionHTTP(0, "Malformed URL: " + malEx); } log.trace("POST " + target.toExternalForm()); ARQ.getHttpRequestLogger().trace(target.toExternalForm()); try { this.client = new SystemDefaultHttpClient(); // Always apply a 10 second timeout to obtaining a connection lease from HTTP Client // This prevents a potential lock up this.client.getParams().setLongParameter(ConnManagerPNames.TIMEOUT, TimeUnit.SECONDS.toMillis(10)); // If user has specified time outs apply them now if (this.connectTimeout > 0) this.client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, this.connectTimeout); if (this.readTimeout > 0) this.client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, this.readTimeout); // Enable compression support appropriately HttpContext context = new BasicHttpContext(); if (allowGZip || allowDeflate) { // Apply auth early as the decompressing client we're about // to add will block this being applied later HttpOp.applyAuthentication((AbstractHttpClient) client, serviceURL, context, authenticator); this.client = new DecompressingHttpClient(client); } // Get the actual response stream TypedInputStream stream = HttpOp.execHttpPostFormStream(serviceURL, this, contentTypeResult, client, context, authenticator); if (stream == null) throw new QueryExceptionHTTP(404); return execCommon(stream); } catch (HttpException httpEx) { // Unwrap and re-wrap the HTTP Exception responseCode = httpEx.getResponseCode(); throw new QueryExceptionHTTP(responseCode, "Error making the query, see cause for details", httpEx.getCause()); } }
From source file:com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport.java
public static void applyHttpSettings(HttpRequest httpMethod, Settings settings) { // user agent? String userAgent = settings.getString(HttpSettings.USER_AGENT, null); if (userAgent != null && userAgent.length() > 0) httpMethod.setHeader("User-Agent", userAgent); // timeout?/*from www .j a v a2 s. c o m*/ long timeout = settings.getLong(HttpSettings.SOCKET_TIMEOUT, HttpSettings.DEFAULT_SOCKET_TIMEOUT); httpMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, (int) timeout); }
From source file:anhttpclient.impl.DefaultWebBrowser.java
/** * Makes default initialization of HttpMethodBase before any request * such as cookie policy, retrycount, timeout * * @param httpMethodBase {@link HttpRequestBase} for making default initialization *//* w w w.j a v a2s. c om*/ private void setDefaultMethodParams(final HttpRequestBase httpMethodBase) { httpMethodBase.getParams().setBooleanParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); httpMethodBase.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // We use here DefaultHttpMethodRetryHandler with <b>true</b> parameter // because we suppose that if method was successfully sent its headers // it could also be retried if (AbstractHttpClient.class.isAssignableFrom(httpClient.getClass())) { ((AbstractHttpClient) httpClient) .setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, true)); } httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout); }
From source file:org.apache.jena.sparql.engine.http.HttpQuery.java
private InputStream execPost() throws QueryExceptionHTTP { URL target = null;/*ww w. ja va 2s . c om*/ try { target = new URL(serviceURL); } catch (MalformedURLException malEx) { throw new QueryExceptionHTTP(0, "Malformed URL: " + malEx); } log.trace("POST " + target.toExternalForm()); ARQ.getHttpRequestLogger().trace(target.toExternalForm()); try { // Select the appropriate HttpClient to use this.selectClient(); // Always apply a 10 second timeout to obtaining a connection lease from HTTP Client // This prevents a potential lock up this.client.getParams().setLongParameter(ConnManagerPNames.TIMEOUT, TimeUnit.SECONDS.toMillis(10)); // If user has specified time outs apply them now if (this.connectTimeout > 0) this.client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, this.connectTimeout); if (this.readTimeout > 0) this.client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, this.readTimeout); // Enable compression support appropriately HttpContext context = new BasicHttpContext(); if (allowGZip || allowDeflate) { // Apply auth early as the decompressing client we're about // to add will block this being applied later HttpOp.applyAuthentication((AbstractHttpClient) client, serviceURL, context, authenticator); this.client = new DecompressingHttpClient(client); } // Get the actual response stream TypedInputStream stream = HttpOp.execHttpPostFormStream(serviceURL, this, contentTypeResult, client, context, authenticator); if (stream == null) throw new QueryExceptionHTTP(404); return execCommon(stream); } catch (HttpException httpEx) { throw rewrap(httpEx); } }
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 {// ww w. ja v a 2 s. 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:no.kantega.kwashc.server.test.SSLCipherSuiteTest.java
private HttpResponse checkClientForCiphers(Site site, int httpsPort, HttpClient httpclient, String[] ciphers) throws NoSuchAlgorithmException, KeyManagementException, IOException { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { allowAllTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000); SSLSocket socket = (SSLSocket) sf.createSocket(params); socket.setEnabledCipherSuites(ciphers); URL url = new URL(site.getAddress()); InetSocketAddress address = new InetSocketAddress(url.getHost(), httpsPort); sf.connectSocket(socket, address, null, params); Scheme sch = new Scheme("https", httpsPort, sf); httpclient.getConnectionManager().getSchemeRegistry().register(sch); HttpGet request = new HttpGet( "https://" + url.getHost() + ":" + site.getSecureport() + url.getPath() + "blog"); return httpclient.execute(request); }
From source file:org.lightcouch.CouchDbClientBase.java
/** * @return {@link DefaultHttpClient} instance. *///from w w w. j av a 2 s . co m private HttpClient createHttpClient(CouchDbProperties props) { DefaultHttpClient httpclient = null; try { SchemeSocketFactory ssf = null; if (props.getProtocol().equals("https")) { TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { trustManager }, null); ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SSLSocket socket = (SSLSocket) ssf.createSocket(null); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); } else { ssf = PlainSocketFactory.getSocketFactory(); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf)); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry); httpclient = new DefaultHttpClient(ccm); host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol()); context = new BasicHttpContext(); // Http params httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout()); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout()); int maxConnections = props.getMaxConnections(); if (maxConnections != 0) { ccm.setMaxTotal(maxConnections); ccm.setDefaultMaxPerRoute(maxConnections); } if (props.getProxyHost() != null) { HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort()); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // basic authentication if (props.getUsername() != null && props.getPassword() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()), new UsernamePasswordCredentials(props.getUsername(), props.getPassword())); props.clearPassword(); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth); context.setAttribute(ClientContext.AUTH_CACHE, authCache); } // request interceptor httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws IOException { if (log.isInfoEnabled()) log.info(">> " + request.getRequestLine()); } }); // response interceptor httpclient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws IOException { validate(response); if (log.isInfoEnabled()) log.info("<< Status: " + response.getStatusLine().getStatusCode()); } }); } catch (Exception e) { log.error("Error Creating HTTP client. " + e.getMessage()); throw new IllegalStateException(e); } return httpclient; }