List of usage examples for org.apache.commons.httpclient HttpClient getHttpConnectionManager
public HttpConnectionManager getHttpConnectionManager()
From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java
private HttpClient initClient(Map<Object, Object> properties) { /* Retrieve Connection Timeout from Properties if set */ int conTimeout = DEFAULT_CON_TIMEOUT; if (properties != null && properties.containsKey(IConnectionPropertyConstants.CON_TIMEOUT)) conTimeout = (Integer) properties.get(IConnectionPropertyConstants.CON_TIMEOUT); /* Create a new HttpClient */ HttpClient client = new HttpClient(new SimpleHttpConnectionManager(true)); /* Socket Timeout - Max. time to wait for an answer */ client.getHttpConnectionManager().getParams().setSoTimeout(conTimeout); /* Connection Timeout - Max. time to wait for a connection */ client.getHttpConnectionManager().getParams().setConnectionTimeout(conTimeout); return client; }
From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java
/** * Generates a reusable http client wrapper which can be given to {@link #fireRequest(HttpClientWrapper, String, Method, Map, Object, boolean)} * as an efficiency mechanism//www. ja v a 2 s. c o m * * @param multiThreaded true if you want to allow the client to run in multiple threads * @param idleConnectionTimeout if this is 0 then it will use the defaults, otherwise connections will be timed out after this long (ms) * @param cookies to send along with every request from this client * @return the reusable http client wrapper */ public static HttpClientWrapper makeReusableHttpClient(boolean multiThreaded, int idleConnectionTimeout, Cookie[] cookies) { HttpClientWrapper wrapper; HttpClient client; MultiThreadedHttpConnectionManager connectionManager = null; if (multiThreaded) { connectionManager = new MultiThreadedHttpConnectionManager(); client = new HttpClient(connectionManager); } else { client = new HttpClient(); } if (idleConnectionTimeout <= 0) { idleConnectionTimeout = 5000; } client.getHttpConnectionManager().closeIdleConnections(idleConnectionTimeout); client.getHttpConnectionManager().getParams().setConnectionTimeout(idleConnectionTimeout); // create the initial state HttpState initialState = new HttpState(); if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; org.apache.commons.httpclient.Cookie mycookie = new org.apache.commons.httpclient.Cookie( c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure()); initialState.addCookie(mycookie); } client.setState(initialState); } // set some defaults client.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); wrapper = new HttpClientWrapper(client, connectionManager, initialState); return wrapper; }
From source file:org.scohen.juploadr.upload.HttpClientFactory.java
public static HttpClient getHttpClient(CommunityAccount account) { HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager()); Protocol http;//from www . j a v a2 s .c o m if (account.isBandwidthLimited()) { http = new Protocol(HTTP, new BandwidthLimitingProtocolSocketFactory(account.getBandwidth()), 80); } else { http = new Protocol(HTTP, new DefaultProtocolSocketFactory(), 80); } Protocol.registerProtocol(HTTP, http); NetActivator activator = NetActivator.getDefault(); IProxyService proxyService = activator.getProxyService(); String home = ((IConfigurationElement) account.getConfiguration().getParent()).getAttribute("home"); //$NON-NLS-1$ home = Core.furnishWebUrl(home); IProxyData proxyData = null; try { IProxyData[] select = proxyService.select(new URI(home)); if (select.length > 0) proxyData = select[0]; } catch (URISyntaxException e) { activator.logError(Messages.HttpClientFactory_bad_uri_for_proxy, e); } finally { activator.ungetProxyService(proxyService); } if (proxyData != null && proxyData.getHost() != null) { String proxyHost = proxyData.getHost(); String proxyPassword = proxyData.getPassword(); String proxyUsername = proxyData.getUserId(); int proxyPort = proxyData.getPort(); HostConfiguration hc = client.getHostConfiguration(); if (proxyPort < 0) hc.setHost(proxyHost); else hc.setProxy(proxyHost, proxyPort); if (proxyData.isRequiresAuthentication() && proxyUsername.length() > 0) { Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword); client.getParams().setAuthenticationPreemptive(true); AuthScope scope = new AuthScope(proxyHost, proxyPort); client.getState().setProxyCredentials(scope, creds); } } client.getHttpConnectionManager().getParams().setConnectionTimeout(60000); client.getHttpConnectionManager().getParams().setSoTimeout(60000); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); return client; }
From source file:org.soitoolkit.commons.mule.mime.MimeUtil.java
public static String sendFileAsMultipartHttpPost(String targetURL, File targetFile, String partName, boolean expectHeader, int timeoutMs) { logger.debug("Send file {} to url {}", targetFile.getAbsolutePath(), targetURL); String response = null;/*from w w w. j a v a 2 s . com*/ PostMethod filePost = new PostMethod(targetURL); filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, expectHeader); try { Part[] parts = { new FilePart(partName, targetFile) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeoutMs); int status = client.executeMethod(filePost); logger.debug("Send done, http status: {}", status); if (status == HttpStatus.SC_OK) { response = filePost.getResponseBodyAsString(); logger.debug("Send done, http response: {}", response); } else { String errorText = HttpStatus.getStatusText(status); throw new RuntimeException("HTTP Error Code: " + status + "HTTP Error Text: " + errorText); } } catch (IOException e) { throw new RuntimeException(e); } finally { filePost.releaseConnection(); } return response; }
From source file:org.sonar.report.pdf.util.FileUploader.java
public static void upload(final File file, final String url, String username, String password) { PostMethod filePost = new PostMethod(url); try {//from w w w . j a v a2 s . c o m LOG.info("Uploading PDF to server..."); Part[] parts = { new FilePart("upload", file) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) { client.getParams().setAuthenticationPreemptive(true); Credentials credentials = new UsernamePasswordCredentials(username, password); client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), credentials); } client.getHttpConnectionManager().getParams().setConnectionTimeout(10000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { LOG.info("PDF uploaded."); } else { LOG.error("Something went wrong storing the PDF at server side. Status: " + status); } } catch (Exception ex) { LOG.error("Something went wrong storing the PDF at server side", ex); ex.printStackTrace(); } finally { filePost.releaseConnection(); } }
From source file:org.sonatype.nexus.bundle.launcher.support.RequestUtils.java
/** * Execute HttpMethod with default Nexus admin credentials * * @param method/*from ww w . j a v a 2 s . c o m*/ * @return * @throws HttpException * @throws IOException */ public static HttpMethod executeHTTPClientMethodAsAdmin(final HttpMethod method) throws HttpException, IOException { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin123")); List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); httpClient.getParams().setAuthenticationPreemptive(true); try { httpClient.executeMethod(method); method.getResponseBodyAsString(); // forced consumption of response I guess return method; } finally { method.releaseConnection(); // force socket cleanup HttpConnectionManager mgr = httpClient.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } }
From source file:org.sonatype.nexus.integrationtests.NexusRestClient.java
/** * Execute a HTTPClient method, optionally in the context of a test. * <p/>//from w w w.ja va2 s . co m * NOTE: Before being returned, {@link org.apache.commons.httpclient.HttpMethod#releaseConnection()} is called on the {@link org.apache.commons.httpclient.HttpMethod} instance, * therefore subsequent calls to get response body as string may return nulls. * * @param method the method to execute * @param useTestContext if true, execute this request in the context of a Test, false means ignore the testContext * settings * @return the HttpMethod instance passed into this method * @throws java.io.IOException */ public HttpMethod executeHTTPClientMethod(final HttpMethod method, final boolean useTestContext) throws IOException { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000); if (useTestContext) { if (testContext.isSecureTest()) { httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(testContext.getUsername(), testContext.getPassword())); List<String> authPrefs = new ArrayList<String>(1); authPrefs.add(AuthPolicy.BASIC); httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); httpClient.getParams().setAuthenticationPreemptive(true); } } try { httpClient.executeMethod(method); method.getResponseBodyAsString(); // forced consumption of response I guess return method; } finally { method.releaseConnection(); // force socket cleanup HttpConnectionManager mgr = httpClient.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.HttpClientProxyUtil.java
public static void applyProxyToHttpClient(HttpClient httpClient, RemoteStorageContext ctx, Logger logger) { httpClient.setHttpConnectionManager(new CustomMultiThreadedHttpConnectionManager()); // getting the timeout from RemoteStorageContext. The value we get depends on per-repo and global settings. // The value will "cascade" from repo level to global level, see imple of it. int timeout = ctx.getRemoteConnectionSettings().getConnectionTimeout(); // getting the connection pool size, using a little trick to allow us "backdoor" to tune it using system // properties, but defaulting it to the same we had before (httpClient defaults) int connectionPoolSize = SystemPropertiesHelper.getInteger(CONNECTION_POOL_SIZE_KEY, MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout); // httpClient.getHttpConnectionManager().getParams().setTcpNoDelay( true ); httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(connectionPoolSize); // NOTE: connPool is _per_ repo, hence all of those will connect to same host (unless mirrors are used) // so, we are violating intentionally the RFC and we let the whole pool size to chase same host httpClient.getHttpConnectionManager().getParams() .setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, connectionPoolSize); // Setting auth if needed HostConfiguration httpConfiguration = httpClient.getHostConfiguration(); // BASIC and DIGEST auth only RemoteAuthenticationSettings ras = ctx.getRemoteAuthenticationSettings(); boolean isSimpleAuthUsed = false; boolean isNtlmUsed = false; if (ras != null) { List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); if (ras instanceof ClientSSLRemoteAuthenticationSettings) { // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras; // TODO - implement this } else if (ras instanceof NtlmRemoteAuthenticationSettings) { NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authPrefs.add(0, AuthPolicy.NTLM); logger(logger).info("... authentication setup for NTLM domain '{}'", nras.getNtlmDomain()); httpConfiguration.setHost(nras.getNtlmHost()); httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain())); isNtlmUsed = true;/*from w w w . j a va2 s . co m*/ } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; // Using Username/Pwd auth, will not add NTLM logger(logger).info("... authentication setup for remote storage with username '{}'", uras.getUsername()); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword())); isSimpleAuthUsed = true; } httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } RemoteProxySettings rps = ctx.getRemoteProxySettings(); boolean isProxyUsed = false; if (rps.isEnabled()) { isProxyUsed = true; logger(logger).info("... proxy setup with host '{}'", rps.getHostname()); httpConfiguration.setProxy(rps.getHostname(), rps.getPort()); // check if we have non-proxy hosts if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) { Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size()); for (String nonProxyHostRegex : rps.getNonProxyHosts()) { try { nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE)); } catch (PatternSyntaxException e) { logger(logger).warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e); } } httpConfiguration.getParams().setParameter( CustomMultiThreadedHttpConnectionManager.NON_PROXY_HOSTS_PATTERNS_KEY, nonProxyHostPatterns); } if (rps.getProxyAuthentication() != null) { ras = rps.getProxyAuthentication(); List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); if (ras instanceof ClientSSLRemoteAuthenticationSettings) { // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras; // TODO - implement this } else if (ras instanceof NtlmRemoteAuthenticationSettings) { NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras; // Using NTLM auth, adding it as first in policies authPrefs.add(0, AuthPolicy.NTLM); if (ctx.getRemoteAuthenticationSettings() != null && (ctx .getRemoteAuthenticationSettings() instanceof NtlmRemoteAuthenticationSettings)) { logger(logger).warn("... Apache Commons HttpClient 3.x is unable to use NTLM auth scheme\n" + " for BOTH server side and proxy side authentication!\n" + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n" + " if you have to use NTLM proxy, otherwise it will not work!\n" + " *** SERVER SIDE AUTH OVERRIDDEN"); } logger(logger).info("... proxy authentication setup for NTLM domain '{}'", nras.getNtlmDomain()); httpConfiguration.setHost(nras.getNtlmHost()); httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(), nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain())); isNtlmUsed = true; } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) { UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras; // Using Username/Pwd auth, will not add NTLM logger(logger).info("... proxy authentication setup for remote storage with username '{}'", uras.getUsername()); httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword())); } httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } // set preemptive only for simplest scenario: // no proxy and BASIC auth is used if (isSimpleAuthUsed && !isProxyUsed) { logger(logger) .info("... simple scenario: simple authentication used with no proxy in between target and us," + " will use preemptive authentication"); // we have authentication, let's do it preemptive httpClient.getParams().setAuthenticationPreemptive(true); } // mark the fact that NTLM is in use // but ONLY IF IT CHANGED! // Otherwise, doing it always, actually marks the ctx itself as "changed", causing an avalanche of other // consequences, like resetting all the HTTP clients of all remote storages (coz they think there is a change // in proxy or remote connection settings, etc). final Boolean isNtlmUsedOldValue = (Boolean) ctx.getContextObject(NTLM_IS_IN_USE_KEY); if (isNtlmUsedOldValue == null || isNtlmUsedOldValue.booleanValue() != isNtlmUsed) { if (isNtlmUsed) { ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.TRUE); } else { ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.FALSE); } } }
From source file:org.tsaap.lti.tp.ResourceLink.java
/** * Performs an HTTP POST request./* w w w . java 2s. co m*/ * * @param url URL to send request to * @param params map of parameter values to be passed * @param header values to include in the request header * @return response returned from request, null if an error occurred */ private String doPostRequest(String url, NameValuePair[] params, Map<String, String> header, StringRequestEntity entity) { String fileContent = null; HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(TIMEOUT); PostMethod httpPost = new PostMethod(url); httpPost.setFollowRedirects(false); httpPost.addParameters(params); try { if (entity != null) { httpPost.setRequestEntity(entity); } if (header != null) { String name; for (Iterator<String> iter = header.keySet().iterator(); iter.hasNext();) { name = iter.next(); httpPost.addRequestHeader(name, header.get(name)); } } httpPost.setURI(new URI(url, false)); int resp = client.executeMethod(httpPost); if (resp < 400) { fileContent = httpPost.getResponseBodyAsString(); } } catch (IOException e) { fileContent = null; } httpPost.releaseConnection(); return fileContent; }
From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java
private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) { logger.finest("Fetching content using HttpClient....user-Id: " + tokenId); HttpClient hc = new HttpClient(); hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000); HttpMethod method = new GetMethod(href); method.addRequestHeader("xx-wings-user-id", tokenId); ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>(); Set<String> keys = requestParameters.keySet(); for (String key : keys) { String value = requestParameters.get(key); nvpList.add(new NameValuePair(key, value)); }// w w w . ja v a 2 s . co m String qs = method.getQueryString(); if (qs != null) { String[] nvPairs = qs.split("&"); for (String nvPair : nvPairs) { String[] mapping = nvPair.split("="); nvpList.add(new NameValuePair(mapping[0], mapping[1])); } } method.setFollowRedirects(true); NameValuePair[] nvps = new NameValuePair[nvpList.size()]; nvps = nvpList.toArray(nvps); method.setQueryString(nvps); byte[] content = null; Header[] headers = null; try { hc.executeMethod(method); content = method.getResponseBody(); headers = method.getResponseHeaders(); } catch (HttpException e) { logger.log(Level.SEVERE, e.getMessage(), e); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); } return new Response(content, headers); }