List of usage examples for org.apache.commons.httpclient HttpClient setHostConfiguration
public void setHostConfiguration(HostConfiguration paramHostConfiguration)
From source file:com.trendmicro.hdfs.webdav.test.MiniClusterTestUtil.java
public HttpClient getClient() { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost("localhost"); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(hostConfig, 100); connectionManager.setParams(params); HttpClient client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); return client; }
From source file:dk.netarkivet.viewerproxy.WebProxyTester.java
/** * Test the general integration of the WebProxy access through the running Jetty true: *///from w ww. j a v a 2s .c om @Test public void testJettyIntegration() throws Exception { TestURIResolver uriResolver = new TestURIResolver(); proxy = new WebProxy(uriResolver); try { new Socket(InetAddress.getLocalHost(), httpPort); } catch (IOException e) { fail("Port not in use after starting server"); } // GET request HttpClient client = new HttpClient(); HostConfiguration hc = new HostConfiguration(); String hostName = SystemUtils.getLocalHostName(); hc.setProxy(hostName, httpPort); client.setHostConfiguration(hc); GetMethod get = new GetMethod("http://foo.bar/"); client.executeMethod(get); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); // POST request PostMethod post = new PostMethod("http://foo2.bar/"); post.addParameter("a", "x"); post.addParameter("a", "y"); client.executeMethod(post); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 2, uriResolver.lookupCount); assertEquals("URI resolver lookup should be called with right URI.", new URI("http://foo2.bar/"), uriResolver.lookupRequestArgument); assertEquals("Posted parameter should be received.", 1, uriResolver.lookupRequestParameteres.size()); assertNotNull("Posted parameter should be received.", uriResolver.lookupRequestParameteres.get("a")); assertEquals("Posted parameter should be received.", 2, uriResolver.lookupRequestParameteres.get("a").length); assertEquals("Posted parameter should be received.", "x", uriResolver.lookupRequestParameteres.get("a")[0]); assertEquals("Posted parameter should be received.", "y", uriResolver.lookupRequestParameteres.get("a")[1]); assertEquals("Status code should be what URI resolver gives", 242, post.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", post.getResponseBodyAsString()); post.releaseConnection(); // Request with parameter and portno get = new GetMethod("http://foo2.bar:8090/?baz=boo"); client.executeMethod(get); // Check request received by URIResolver assertEquals("URI resolver lookup should be called.", 3, uriResolver.lookupCount); assertEquals("URI resolver 2 lookup should be called with right URI.", new URI("http://foo2.bar:8090/?baz=boo"), uriResolver.lookupRequestArgument); assertEquals("Status code should be what URI resolver gives", 242, get.getStatusCode()); assertEquals("Body should contain what URI resolver wrote", "Test", get.getResponseBodyAsString()); get.releaseConnection(); }
From source file:com.legstar.http.client.CicsHttp.java
/** * Create a reusable HTTP Client with a set of parameters that match * the remote CICS Server characteristics. At this stage, the HTTPClient is not * associated with a state and a method yet. * @param cicsHttpEndpoint the connection configuration * @return the new HTTP Client//from w w w.j a v a2s . co m */ protected HttpClient createHttpClient(final CicsHttpEndpoint cicsHttpEndpoint) { if (_log.isDebugEnabled()) { _log.debug("enter createHttpClient()"); } HttpClientParams params = new HttpClientParams(); /* Consider that if server is failing to respond, we should never retry. * A system such as CICS should always be responsive unless something * bad is happening in which case, retry makes things worse. */ DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); params.setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); /* Preemptive authentication forces the first HTTP payload to hold * credentials. This bypasses the inefficient default mechanism that * expects a 401 reply on the first request and then re-issues the same * request again with credentials.*/ params.setAuthenticationPreemptive(true); /* Set the receive time out. */ params.setSoTimeout(cicsHttpEndpoint.getReceiveTimeout()); /* Tell the connection manager how long we are prepared to wait * for a connection. */ params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, cicsHttpEndpoint.getConnectTimeout()); /* Disable Nagle algorithm */ params.setBooleanParameter(HttpConnectionParams.TCP_NODELAY, true); HttpClient httpClient = new HttpClient(params); httpClient.setHostConfiguration(createHostConfiguration(cicsHttpEndpoint)); return httpClient; }
From source file:de.pdark.dsmp.ProxyDownload.java
/** * Do the download.//ww w . java2 s . co m * * @throws IOException * @throws DownloadFailed */ public void download() throws IOException, DownloadFailed { if (!config.isAllowed(url)) { throw new DownloadFailed( "HTTP/1.1 " + HttpStatus.SC_FORBIDDEN + " Download denied by rule in DSMP config"); } // If there is a status file in the cache, return it instead of trying it again // As usual with caches, this one is a key area which will always cause // trouble. // TODO There should be a simple way to get rid of the cached statuses // TODO Maybe retry a download after a certain time? File statusFile = new File(dest.getAbsolutePath() + ".status"); if (statusFile.exists()) { try { FileReader r = new FileReader(statusFile); char[] buffer = new char[(int) statusFile.length()]; int len = r.read(buffer); r.close(); String status = new String(buffer, 0, len); throw new DownloadFailed(status); } catch (IOException e) { log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e); } } mkdirs(); HttpClient client = new HttpClient(); String msg = ""; if (config.useProxy(url)) { Credentials defaultcreds = new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()); AuthScope scope = new AuthScope(config.getProxyHost(), config.getProxyPort(), AuthScope.ANY_REALM); HostConfiguration hc = new HostConfiguration(); hc.setProxy(config.getProxyHost(), config.getProxyPort()); client.setHostConfiguration(hc); client.getState().setProxyCredentials(scope, defaultcreds); msg = "via proxy "; } log.info("Downloading " + msg + "to " + dest.getAbsolutePath()); GetMethod get = new GetMethod(url.toString()); get.setFollowRedirects(true); try { int status = client.executeMethod(get); log.info("Download status: " + status); if (0 == 1 && log.isDebugEnabled()) { Header[] header = get.getResponseHeaders(); for (Header aHeader : header) log.debug(aHeader.toString().trim()); } log.info("Content: " + valueOf(get.getResponseHeader("Content-Length")) + " bytes; " + valueOf(get.getResponseHeader("Content-Type"))); if (status != HttpStatus.SC_OK) { // Remember "File not found" if (status == HttpStatus.SC_NOT_FOUND) { try { FileWriter w = new FileWriter(statusFile); w.write(get.getStatusLine().toString()); w.close(); } catch (IOException e) { log.warn("Error writing 'File not found'-Status to " + statusFile.getAbsolutePath(), e); } } throw new DownloadFailed(get); } File dl = new File(dest.getAbsolutePath() + ".new"); OutputStream out = new BufferedOutputStream(new FileOutputStream(dl)); IOUtils.copy(get.getResponseBodyAsStream(), out); out.close(); File bak = new File(dest.getAbsolutePath() + ".bak"); if (bak.exists()) bak.delete(); if (dest.exists()) dest.renameTo(bak); dl.renameTo(dest); } finally { get.releaseConnection(); } }
From source file:com.orange.mmp.net.http.HttpConnectionManager.java
public Connection getConnection() throws MMPNetException { SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager(); HttpClientParams defaultHttpParams = new HttpClientParams(); defaultHttpParams.setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); defaultHttpParams.setParameter(HttpConnectionParams.TCP_NODELAY, true); defaultHttpParams.setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false); defaultHttpParams.setParameter(HttpConnectionParams.SO_LINGER, 0); defaultHttpParams.setParameter(HttpClientParams.MAX_REDIRECTS, 3); defaultHttpParams.setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, false); HttpClient httpClient2 = new HttpClient(defaultHttpParams, shcm); if (HttpConnectionManager.proxyHost != null) { defaultHttpParams.setParameter("http.route.default-proxy", new HttpHost(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort)); // TODO Host configuration ! if (HttpConnectionManager.proxyHost != null/* && this.useProxy*/) { HostConfiguration config = new HostConfiguration(); config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort); httpClient2.setHostConfiguration(config); } else {/*from www. ja v a 2 s . com*/ HostConfiguration config = new HostConfiguration(); config.setProxyHost(null); httpClient2.setHostConfiguration(config); } } return new HttpConnection(httpClient2); }
From source file:net.sf.webissues.core.WebIssuesClientManager.java
protected HttpClient createHttpClient(AbstractWebLocation location) { HttpClient httpClient = new HttpClient(); httpClient.getParams().setAuthenticationPreemptive(true); HttpConnectionManager connectionManager = WebIssuesClientManager.getConnectionManager(); httpClient.setHttpConnectionManager(connectionManager); connectionManager.getParams().setConnectionTimeout(8000); connectionManager.getParams().setSoTimeout(8000); httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); WebUtil.configureHttpClient(httpClient, WebIssuesClientManager.USER_AGENT); httpClient.setHostConfiguration(WebUtil.createHostConfiguration(httpClient, location, null)); return httpClient; }
From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { this.getLog().debug("Entering."); this.getLog().info("Component:" + this.componentName); // si el informe el solo para el padre y es un hijo salimos // si es un hijo y no est definido el component salimos if (isParentProject() || (parentOnly && isEmpty(componentName))) { return;/*w w w . j ava 2 s .c om*/ } versionName = getVersionNameFromProject(); // inicializamos el gestor de peticiones this.httpRequest = new HttpRequest(this.getLog()); // inicializamos la url del Bugzilla this.bugzillaUrl = this.project.getIssueManagement().getUrl(); // preparamos el cliente HTTP para las peticiones final HttpClient client = new HttpClient(); final HttpClientParams clientParams = client.getParams(); clientParams.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); final HttpState state = new HttpState(); final HostConfiguration hc = new HostConfiguration(); client.setHostConfiguration(hc); client.setState(state); this.determineProxy(client); if (!performLogin(client)) { throw new MojoExecutionException( "The username or password you entered is not valid. Cannot login in Bugzilla: " + bugzillaUrl); } final String bugsIds = this.getBugList(client); final Document bugsDocument = this.getBugsDocument(client, bugsIds); builChangesXML(bugsDocument); this.getLog().debug("Exiting."); }
From source file:colt.nicity.performance.agent.LatentHttpPump.java
private org.apache.commons.httpclient.HttpClient createApacheClient(String host, int port, int maxConnections, int socketTimeoutInMillis) { HttpConnectionManager connectionManager = createConnectionManager(maxConnections); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient( connectionManager);/*from ww w.j av a 2 s. co m*/ client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109); client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0); client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeoutInMillis > 0 ? socketTimeoutInMillis : 0); HostConfiguration hostConfiguration = new HostConfiguration(); configureSsl(hostConfiguration, host, port); configureProxy(hostConfiguration); client.setHostConfiguration(hostConfiguration); return client; }
From source file:de.juwimm.cms.common.http.HttpClientWrapper.java
public void setHostConfiguration(HttpClient client, URL targetURL) { int port = targetURL.getPort(); String host = targetURL.getHost(); HostConfiguration config = hostMap.get(host + ":" + port); if (config == null) { config = new HostConfiguration(); if (port == -1) { if (targetURL.getProtocol().equalsIgnoreCase("https")) { port = 443;//w w w .j ava 2s . c o m } else { port = 80; } } config.setHost(host, port, targetURL.getProtocol()); } // in the meantime HttpProxyUser and HttpProxyPasword might have changed // (DlgUsernamePassword) or now trying NTLM instead of BASE // authentication if (getHttpProxyHost() != null && getHttpProxyPort() != null && getHttpProxyHost().length() > 0 && getHttpProxyPort().length() > 0) { client.getParams().setAuthenticationPreemptive(true); int proxyPort = new Integer(getHttpProxyPort()).intValue(); config.setProxy(getHttpProxyHost(), proxyPort); if (getHttpProxyUser() != null && getHttpProxyUser().length() > 0) { Credentials proxyCred = null; if (isUseNTproxy()) { proxyCred = new NTCredentials(getHttpProxyUser(), getHttpProxyPassword(), getHttpProxyHost(), ""); } else { proxyCred = new UsernamePasswordCredentials(getHttpProxyUser(), getHttpProxyPassword()); } client.getState().setProxyCredentials(AUTHSCOPE_ANY, proxyCred); } } hostMap.put(host + ":" + port, config); client.setHostConfiguration(config); }
From source file:com.datos.vfs.provider.http.HttpClientFactory.java
/** * Creates a new connection to the server. * @param builder The HttpFileSystemConfigBuilder. * @param scheme The protocol.//from w w w. ja v a 2s. com * @param hostname The hostname. * @param port The port number. * @param username The username. * @param password The password * @param fileSystemOptions The file system options. * @return a new HttpClient connection. * @throws FileSystemException if an error occurs. * @since 2.0 */ public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme, final String hostname, final int port, final String username, final String password, final FileSystemOptions fileSystemOptions) throws FileSystemException { HttpClient client; try { final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); final HttpConnectionManagerParams connectionMgrParams = mgr.getParams(); client = new HttpClient(mgr); final HostConfiguration config = new HostConfiguration(); config.setHost(hostname, port, scheme); if (fileSystemOptions != null) { final String proxyHost = builder.getProxyHost(fileSystemOptions); final int proxyPort = builder.getProxyPort(fileSystemOptions); if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) { config.setProxy(proxyHost, proxyPort); } final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions); if (proxyAuth != null) { final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD }); if (authData != null) { final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials( UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, null))); final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT); client.getState().setProxyCredentials(scope, proxyCreds); } if (builder.isPreemptiveAuth(fileSystemOptions)) { final HttpClientParams httpClientParams = new HttpClientParams(); httpClientParams.setAuthenticationPreemptive(true); client.setParams(httpClientParams); } } final Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { client.getState().addCookies(cookies); } } /** * ConnectionManager set methods must be called after the host & port and proxy host & port * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams * tries to locate the host configuration. */ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions)); connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions)); connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions)); connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions)); client.setHostConfiguration(config); if (username != null) { final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password); final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT); client.getState().setCredentials(scope, creds); } } catch (final Exception exc) { throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname); } return client; }