List of usage examples for org.apache.commons.httpclient HostConfiguration setHost
public void setHost(String paramString, int paramInt, Protocol paramProtocol)
From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java
/** * getting host configuration to support standard http/s, proxy and NTLM support * * @param client active HttpClient// w w w. ja v a 2 s .c om * @param msgCtx active MessageContext * @param targetURL the target URL * @return a HostConfiguration set up with proxy information * @throws AxisFault if problems occur */ protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext msgCtx, URL targetURL) throws AxisFault { boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx); int port = targetURL.getPort(); String protocol = targetURL.getProtocol(); if (port == -1) { if (PROTOCOL_HTTP.equals(protocol)) { port = 80; } else if (PROTOCOL_HTTPS.equals(protocol)) { port = 443; } } // to see the host is a proxy and in the proxy list - available in axis2.xml HostConfiguration config = new HostConfiguration(); // one might need to set his own socket factory. Let's allow that case as well. Protocol protocolHandler = (Protocol) msgCtx.getOptions() .getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER); // setting the real host configuration // I assume the 90% case, or even 99% case will be no protocol handler case. if (protocolHandler == null) { config.setHost(targetURL.getHost(), port, targetURL.getProtocol()); } else { config.setHost(targetURL.getHost(), port, protocolHandler); } if (isAuthenticationEnabled) { // Basic, Digest, NTLM and custom authentications. this.setAuthenticationInfo(client, msgCtx, config); } // proxy configuration if (HTTPProxyConfigurationUtil.isProxyEnabled(msgCtx, targetURL)) { if (log.isDebugEnabled()) { log.debug("Configuring HTTP proxy."); } HTTPProxyConfigurationUtil.configure(msgCtx, client, config); } return config; }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * getting host configuration to support standard http/s, proxy and NTLM * support//w w w .jav a 2s. c o m * * @param client * active HttpClient * @param msgCtx * active MessageContext * @param targetURL * the target URL * @return a HostConfiguration set up with proxy information * @throws AxisFault * if problems occur */ protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext msgCtx, URL targetURL) throws AxisFault { boolean isAuthenticationEnabled = isAuthenticationEnabled(msgCtx); int port = targetURL.getPort(); String protocol = targetURL.getProtocol(); if (port == -1) { if (HTTPTransportConstants.PROTOCOL_HTTP.equals(protocol)) { port = 80; } else if (HTTPTransportConstants.PROTOCOL_HTTPS.equals(protocol)) { port = 443; } } // to see the host is a proxy and in the proxy list - available in // axis2.xml HostConfiguration config = client.getHostConfiguration(); if (config == null) { config = new HostConfiguration(); } // one might need to set his own socket factory. Let's allow that case // as well. Protocol protocolHandler = (Protocol) msgCtx.getOptions() .getProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER); // setting the real host configuration // I assume the 90% case, or even 99% case will be no protocol handler // case. if (protocolHandler == null) { config.setHost(targetURL.getHost(), port, targetURL.getProtocol()); } else { config.setHost(targetURL.getHost(), port, protocolHandler); } if (isAuthenticationEnabled) { // Basic, Digest, NTLM and custom authentications. this.setAuthenticationInfo(client, msgCtx, config); } // proxy configuration if (HTTPProxyConfigurator.isProxyEnabled(msgCtx, targetURL)) { if (log.isDebugEnabled()) { log.debug("Configuring HTTP proxy."); } HTTPProxyConfigurator.configure(msgCtx, client, config); } return config; }
From source file:org.apache.cactus.internal.client.connector.http.HttpClientConnectionHelper.java
/** * {@inheritDoc}/*from w w w . java 2 s . com*/ * @see ConnectionHelper#connect(WebRequest, Configuration) */ public HttpURLConnection connect(WebRequest theRequest, Configuration theConfiguration) throws Throwable { URL url = new URL(this.url); HttpState state = new HttpState(); // Choose the method that we will use to post data : // - If at least one parameter is to be sent in the request body, then // we are doing a POST. // - If user data has been specified, then we are doing a POST if (theRequest.getParameterNamesPost().hasMoreElements() || (theRequest.getUserData() != null)) { this.method = new PostMethod(); } else { this.method = new GetMethod(); } // Add Authentication headers, if necessary. This is the first // step to allow authentication to add extra headers, HTTP parameters, // etc. Authentication authentication = theRequest.getAuthentication(); if (authentication != null) { authentication.configure(state, this.method, theRequest, theConfiguration); } // Add the parameters that need to be passed as part of the URL url = HttpUtil.addHttpGetParameters(theRequest, url); this.method.setFollowRedirects(false); this.method.setPath(UrlUtil.getPath(url)); this.method.setQueryString(UrlUtil.getQuery(url)); // Sets the content type this.method.setRequestHeader("Content-type", theRequest.getContentType()); // Add the other header fields addHeaders(theRequest); // Add the POST parameters if no user data has been specified (user data // overried post parameters) if (theRequest.getUserData() != null) { addUserData(theRequest); } else { addHttpPostParameters(theRequest); } // Add the cookies to the state state.addCookies(CookieUtil.createHttpClientCookies(theRequest, url)); // Open the connection and get the result HttpClient client = new HttpClient(); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(url.getHost(), url.getPort(), Protocol.getProtocol(url.getProtocol())); client.setState(state); client.executeMethod(hostConfiguration, this.method); // Wrap the HttpClient method in a java.net.HttpURLConnection object return new org.apache.commons.httpclient.util.HttpURLConnection(this.method, url); }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java
/** * Returns an <code>HttpConnection</code> fully ready to attempt * connection. This means it sets the request method (GET or POST), headers, * cookies, and authorization for the URL request. * <p>// ww w. j av a2 s .c om * The request infos are saved into the sample result if one is provided. * * @param u * <code>URL</code> of the URL request * @param httpMethod * GET/PUT/HEAD etc * @param res * sample result to save request infos to * @return <code>HttpConnection</code> ready for .connect * @exception IOException * if an I/O Exception occurs */ protected HttpClient setupConnection(URL u, HttpMethodBase httpMethod, HTTPSampleResult res) throws IOException { String urlStr = u.toString(); org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(urlStr, false); String schema = uri.getScheme(); if ((schema == null) || (schema.length() == 0)) { schema = HTTPConstants.PROTOCOL_HTTP; } final boolean isHTTPS = HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(schema); if (isHTTPS) { SSLManager.getInstance(); // ensure the manager is initialised // we don't currently need to do anything further, as this sets the default https protocol } Protocol protocol = Protocol.getProtocol(schema); String host = uri.getHost(); int port = uri.getPort(); /* * We use the HostConfiguration as the key to retrieve the HttpClient, * so need to ensure that any items used in its equals/hashcode methods are * not changed after use, i.e.: * host, port, protocol, localAddress, proxy * */ HostConfiguration hc = new HostConfiguration(); hc.setHost(host, port, protocol); // All needed to ensure re-usablility // Set up the local address if one exists final InetAddress inetAddr = getIpSourceAddress(); if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing') hc.setLocalAddress(inetAddr); } else { hc.setLocalAddress(localAddress); // null means use the default } final String proxyHost = getProxyHost(); final int proxyPort = getProxyPortInt(); boolean useStaticProxy = isStaticProxy(host); boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort); if (useDynamicProxy) { hc.setProxy(proxyHost, proxyPort); useStaticProxy = false; // Dynamic proxy overrules static proxy } else if (useStaticProxy) { if (log.isDebugEnabled()) { log.debug("Setting proxy: " + PROXY_HOST + ":" + PROXY_PORT); } hc.setProxy(PROXY_HOST, PROXY_PORT); } Map<HostConfiguration, HttpClient> map = httpClients.get(); // N.B. HostConfiguration.equals() includes proxy settings in the compare. HttpClient httpClient = map.get(hc); if (httpClient != null && resetSSLContext && isHTTPS) { httpClient.getHttpConnectionManager().closeIdleConnections(-1000); httpClient = null; JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance(); sslMgr.resetContext(); resetSSLContext = false; } if (httpClient == null) { httpClient = new HttpClient(new SimpleHttpConnectionManager()); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(RETRY_COUNT, false)); if (log.isDebugEnabled()) { log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient)); } httpClient.setHostConfiguration(hc); map.put(hc, httpClient); } else { if (log.isDebugEnabled()) { log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient)); } } // Set up any required Proxy credentials if (useDynamicProxy) { String user = getProxyUser(); if (user.length() > 0) { httpClient.getState().setProxyCredentials( new AuthScope(proxyHost, proxyPort, null, AuthScope.ANY_SCHEME), new NTCredentials(user, getProxyPass(), localHost, PROXY_DOMAIN)); } else { httpClient.getState().clearProxyCredentials(); } } else { if (useStaticProxy) { if (PROXY_USER.length() > 0) { httpClient.getState().setProxyCredentials( new AuthScope(PROXY_HOST, PROXY_PORT, null, AuthScope.ANY_SCHEME), new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN)); } } else { httpClient.getState().clearProxyCredentials(); } } int rto = getResponseTimeout(); if (rto > 0) { httpMethod.getParams().setSoTimeout(rto); } int cto = getConnectTimeout(); if (cto > 0) { httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(cto); } // Allow HttpClient to handle the redirects: httpMethod.setFollowRedirects(getAutoRedirects()); // a well-behaved browser is supposed to send 'Connection: close' // with the last request to an HTTP server. Instead, most browsers // leave it to the server to close the connection after their // timeout period. Leave it to the JMeter user to decide. if (getUseKeepAlive()) { httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE); } else { httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE); } setConnectionHeaders(httpMethod, u, getHeaderManager(), getCacheManager()); String cookies = setConnectionCookie(httpMethod, u, getCookieManager()); setConnectionAuthorization(httpClient, u, getAuthManager()); if (res != null) { res.setCookies(cookies); } return httpClient; }
From source file:org.codehaus.httpcache4j.client.HTTPClientResponseResolver.java
/** * Determines the HttpClient's request method from the HTTPMethod enum. * * @param method the HTTPCache enum that determines * @param requestURI the request URI./*w w w. j a va2 s .c o m*/ * @return a new HttpMethod subclass. */ protected HttpMethod getMethod(HTTPMethod method, URI requestURI) { if (CONNECT.equals(method)) { HostConfiguration config = new HostConfiguration(); config.setHost(requestURI.getHost(), requestURI.getPort(), requestURI.getScheme()); return new ConnectMethod(config); } else if (DELETE.equals(method)) { return new DeleteMethod(requestURI.toString()); } else if (GET.equals(method)) { return new GetMethod(requestURI.toString()); } else if (HEAD.equals(method)) { return new HeadMethod(requestURI.toString()); } else if (OPTIONS.equals(method)) { return new OptionsMethod(requestURI.toString()); } else if (POST.equals(method)) { return new PostMethod(requestURI.toString()); } else if (PUT.equals(method)) { return new PutMethod(requestURI.toString()); } else if (TRACE.equals(method)) { return new TraceMethod(requestURI.toString()); } else { throw new IllegalArgumentException("Cannot handle method: " + method); } }
From source file:org.eclipse.mylyn.commons.net.WebUtil.java
/** * @since 3.0/* ww w. ja v a2 s . c o m*/ */ public static HostConfiguration createHostConfiguration(HttpClient client, AbstractWebLocation location, IProgressMonitor monitor) { Assert.isNotNull(client); Assert.isNotNull(location); String url = location.getUrl(); String host = WebUtil.getHost(url); int port = WebUtil.getPort(url); configureHttpClientConnectionManager(client); HostConfiguration hostConfiguration = new CloneableHostConfiguration(); configureHttpClientProxy(client, hostConfiguration, location); AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.HTTP); if (credentials != null) { AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); client.getState().setCredentials(authScope, getHttpClientCredentials(credentials, host)); } if (WebUtil.isRepositoryHttps(url)) { AuthenticationCredentials certCredentials = location.getCredentials(AuthenticationType.CERTIFICATE); if (certCredentials == null) { Protocol protocol = new Protocol("https", sslSocketFactory, HTTPS_PORT); //$NON-NLS-1$ hostConfiguration.setHost(host, port, protocol); } else { Protocol protocol = new Protocol("https", //$NON-NLS-1$ (ProtocolSocketFactory) new PollingSslProtocolSocketFactory(certCredentials.getUserName(), certCredentials.getPassword(), null), HTTPS_PORT); hostConfiguration.setHost(host, port, protocol); } } else { Protocol protocol = new Protocol("http", socketFactory, HTTP_PORT); //$NON-NLS-1$ hostConfiguration.setHost(host, port, protocol); } return hostConfiguration; }
From source file:org.eclipse.mylyn.internal.provisional.commons.soap.CommonsHttpSender.java
protected HostConfiguration getHostConfiguration(HttpClient client, MessageContext context, URL targetURL) { TransportClientProperties tcp = TransportClientPropertiesFactory.create(targetURL.getProtocol()); // http or https int port = targetURL.getPort(); boolean hostInNonProxyList = isHostInNonProxyList(targetURL.getHost(), tcp.getNonProxyHosts()); HostConfiguration config = new HostConfiguration(); if (port == -1) { if (targetURL.getProtocol().equalsIgnoreCase("https")) { //$NON-NLS-1$ port = 443; // default port for https being 443 } else { // it must be http port = 80; // default port for http being 80 }/*from w ww . j av a 2s . c om*/ } if (hostInNonProxyList) { config.setHost(targetURL.getHost(), port, targetURL.getProtocol()); } else { if (tcp.getProxyHost().length() == 0 || tcp.getProxyPort().length() == 0) { config.setHost(targetURL.getHost(), port, targetURL.getProtocol()); } else { if (tcp.getProxyUser().length() != 0) { Credentials proxyCred = new UsernamePasswordCredentials(tcp.getProxyUser(), tcp.getProxyPassword()); // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = tcp.getProxyUser().indexOf("\\"); //$NON-NLS-1$ if (domainIndex > 0) { String domain = tcp.getProxyUser().substring(0, domainIndex); if (tcp.getProxyUser().length() > domainIndex + 1) { String user = tcp.getProxyUser().substring(domainIndex + 1); proxyCred = new NTCredentials(user, tcp.getProxyPassword(), tcp.getProxyHost(), domain); } } client.getState().setProxyCredentials(AuthScope.ANY, proxyCred); } int proxyPort = new Integer(tcp.getProxyPort()).intValue(); config.setProxy(tcp.getProxyHost(), proxyPort); } } return config; }
From source file:org.eclipse.virgo.ide.runtime.internal.core.utils.WebDownloadUtils.java
public static Date getLastModifiedDate(String url, IProgressMonitor monitor) { GetMethod method = null;/*from w ww . ja v a 2 s .c o m*/ BufferedInputStream bis = null; FileOutputStream fos = null; try { if (monitor.isCanceled()) { return null; } HttpClient client = new HttpClient(); method = new GetMethod(url); method.setFollowRedirects(true); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(getHost(url), HTTP_PORT, "http"); configureHttpClientProxy(url, client, hostConfiguration); client.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNNECT_TIMEOUT); // Execute the GET method int statusCode = client.executeMethod(hostConfiguration, method); if (statusCode == 200) { if (monitor.isCanceled()) { return null; } Header lastModified = method.getResponseHeader("Last-Modified"); if (lastModified != null) { return DateUtil.parseDate(lastModified.getValue()); } } } catch (Exception e) { } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception e2) { } try { if (bis != null) { bis.close(); } } catch (Exception e2) { } try { if (fos != null) { fos.close(); } } catch (Exception e2) { } } return null; }
From source file:org.eclipse.virgo.ide.runtime.internal.core.utils.WebDownloadUtils.java
public static File downloadFile(String url, File outputPath, IProgressMonitor monitor) { GetMethod method = null;/*from w w w . ja v a 2 s . c o m*/ BufferedInputStream bis = null; FileOutputStream fos = null; File outputFile = null; try { if (monitor.isCanceled()) { return null; } HttpClient client = new HttpClient(); method = new GetMethod(url); method.setFollowRedirects(true); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setHost(getHost(url), HTTP_PORT, "http"); configureHttpClientProxy(url, client, hostConfiguration); client.getHttpConnectionManager().getParams().setSoTimeout(SOCKET_TIMEOUT); client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNNECT_TIMEOUT); // Execute the GET method int statusCode = client.executeMethod(hostConfiguration, method); if (statusCode == 200) { int ix = method.getPath().lastIndexOf('/'); String fileName = method.getPath().substring(ix + 1); monitor.subTask("Downloading file '" + fileName + "'"); if (monitor.isCanceled()) { return null; } Header[] header = method.getResponseHeaders("content-length"); long totalBytes = Long.valueOf(header[0].getValue()); InputStream is = method.getResponseBodyAsStream(); bis = new BufferedInputStream(is); outputFile = new File(outputPath, fileName); fos = new FileOutputStream(outputFile); long bytesRead = 0; byte[] bytes = new byte[8192]; int count = bis.read(bytes); while (count != -1 && count <= 8192) { if (monitor.isCanceled()) { return null; } bytesRead = bytesRead + count; float percent = Float.valueOf(bytesRead) / Float.valueOf(totalBytes) * 100; monitor.subTask("Downloading file '" + fileName + "': " + bytesRead + "bytes/" + totalBytes + "bytes (" + Math.round(percent) + "%)"); fos.write(bytes, 0, count); count = bis.read(bytes); } if (count != -1) { fos.write(bytes, 0, count); } } return outputFile; } catch (Exception e) { ServerCorePlugin.getDefault().getLog().log(new Status(IStatus.ERROR, ServerCorePlugin.PLUGIN_ID, 1, "Error downloading bundle/library", e)); } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception e2) { } try { if (bis != null) { bis.close(); } } catch (Exception e2) { } try { if (fos != null) { fos.close(); } } catch (Exception e2) { } } return null; }
From source file:org.exoplatform.services.common.HttpClientImpl.java
private void setHost(String protocol, String host, int port) throws Exception { MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams para = new HttpConnectionManagerParams(); para.setConnectionTimeout(HTTP_TIMEOUT); para.setDefaultMaxConnectionsPerHost(10); para.setMaxTotalConnections(20);/*ww w . j a va 2s .c om*/ para.setStaleCheckingEnabled(true); manager.setParams(para); http = new HttpClient(manager); http.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); http.getParams().setParameter("http.socket.timeout", new Integer(HTTP_TIMEOUT)); http.getParams().setParameter("http.protocol.content-charset", "UTF-8"); http.getParams().setCookiePolicy(CookiePolicy.RFC_2109); http.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); if (port < 0) port = 80; HostConfiguration hostConfig = http.getHostConfiguration(); hostConfig.setHost(host, port, protocol); String proxyHost = System.getProperty("httpclient.proxy.host"); if (proxyHost == null || proxyHost.trim().length() < 1) return; String proxyPort = System.getProperty("httpclient.proxy.port"); hostConfig.setProxy(proxyHost, Integer.parseInt(proxyPort)); String username = System.getProperty("httpclient.proxy.username"); String password = System.getProperty("httpclient.proxy.password"); String ntlmHost = System.getProperty("httpclient.proxy.ntlm.host"); String ntlmDomain = System.getProperty("httpclient.proxy.ntlm.domain"); Credentials ntCredentials; if (ntlmHost == null || ntlmDomain == null) { ntCredentials = new UsernamePasswordCredentials(username, password); } else { ntCredentials = new NTCredentials(username, password, ntlmHost, ntlmDomain); } http.getState().setProxyCredentials(AuthScope.ANY, ntCredentials); }