List of usage examples for org.apache.commons.httpclient HostConfiguration setProxy
public void setProxy(String paramString, int paramInt)
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPProxcyConfigurator.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. * Proxy settings can be get from axis2.xml, Java proxy settings or can be * override through property in message context. * <p/>/*w w w . ja v a 2 s. c o m*/ * HTTP Proxy setting element format: <parameter name="Proxy"> * <Configuration> <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter> * * @param messageContext * in message context for * @param httpClient * commons-httpclient instance * @param config * commons-httpclient HostConfiguration * @throws AxisFault * if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; // Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(HTTPTransportConstants.ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); } } // If there is runtime proxy settings, these settings will override // settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPProxyConfigurator.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. * Proxy settings can be get from axis2.xml, Java proxy settings or can be * override through property in message context. * <p/>/*from w ww . jav a 2 s. co m*/ * HTTP Proxy setting element format: <parameter name="Proxy"> * <Configuration> <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter> * * @param messageContext * in message context for * @param httpClient * commons-httpclient instance * @param config * commons-httpclient HostConfiguration * @throws AxisFault * if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; // Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(HTTPTransportConstants.ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } } } // If there is runtime proxy settings, these settings will override // settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.axis2.transport.http.ProxyConfiguration.java
public void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { // <parameter name="Proxy"> // <Configuration> // <ProxyHost>example.org</ProxyHost> // <ProxyPort>5678</ProxyPort> // <ProxyUser>EXAMPLE\saminda</ProxyUser> // <ProxyPassword>ppp</ProxyPassword> // </Configuration> // </parameter> Credentials proxyCred = null;/* ww w. j a v a 2 s. co m*/ //Getting configuration values from Axis2.xml Parameter param = messageContext.getConfigurationContext().getAxisConfiguration().getParameter(ATTR_PROXY); if (param != null) { OMElement configurationEle = param.getParameterElement().getFirstElement(); if (configurationEle == null) { throw new AxisFault(ProxyConfiguration.class.getName() + " Configuration element is missing"); } OMElement proxyHostEle = configurationEle.getFirstChildWithName(new QName(PROXY_HOST_ELEMENT)); OMElement proxyPortEle = configurationEle.getFirstChildWithName(new QName(PROXY_PORT_ELEMENT)); OMElement proxyUserEle = configurationEle.getFirstChildWithName(new QName(PROXY_USER_ELEMENT)); OMElement proxyPasswordEle = configurationEle.getFirstChildWithName(new QName(PROXY_PASSWORD_ELEMENT)); if (proxyHostEle == null) { throw new AxisFault(ProxyConfiguration.class.getName() + " ProxyHost element is missing"); } String text = proxyHostEle.getText(); if (text == null) { throw new AxisFault(ProxyConfiguration.class.getName() + " ProxyHost's value is missing"); } this.setProxyHost(text); if (proxyPortEle != null) { this.setProxyPort(Integer.parseInt(proxyPortEle.getText())); } if (proxyUserEle != null) { this.setProxyUser(proxyUserEle.getText()); } if (proxyPasswordEle != null) { this.setProxyPassword(proxyPasswordEle.getText()); } if (this.getProxyUser() == null && this.getProxyUser() == null) { proxyCred = new UsernamePasswordCredentials("", ""); } else { proxyCred = new UsernamePasswordCredentials(this.getProxyUser(), this.getProxyPassword()); } // if the username is in the form "DOMAIN\\user" // then use NTCredentials instead. if (this.getProxyUser() != null) { int domainIndex = this.getProxyUser().indexOf("\\"); if (domainIndex > 0) { String domain = this.getProxyUser().substring(0, domainIndex); if (this.getProxyUser().length() > domainIndex + 1) { String user = this.getProxyUser().substring(domainIndex + 1); proxyCred = new NTCredentials(user, this.getProxyPassword(), this.getProxyHost(), domain); } } } } // Overide the property setting in runtime. HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String host = proxyProperties.getProxyHostName(); if (host == null || host.length() == 0) { throw new AxisFault(ProxyConfiguration.class.getName() + " Proxy host is not available. Host is a MUST parameter"); } else { this.setProxyHost(host); } this.setProxyPort(proxyProperties.getProxyPort()); //Setting credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName == null && password == null) { proxyCred = new UsernamePasswordCredentials("", ""); } else { proxyCred = new UsernamePasswordCredentials(userName, password); } if (userName != null && password != null && domain != null) { proxyCred = new NTCredentials(userName, password, host, domain); } } //Using Java Networking Properties String host = System.getProperty(HTTP_PROXY_HOST); if (host != null) { this.setProxyHost(host); proxyCred = new UsernamePasswordCredentials("", ""); } String port = System.getProperty(HTTP_PROXY_PORT); if (port != null) { this.setProxyPort(Integer.parseInt(port)); } if (proxyCred == null) { throw new AxisFault(ProxyConfiguration.class.getName() + " Minimum proxy credentials are not set"); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCred); config.setProxy(this.getProxyHost(), this.getProxyPort()); }
From source file:org.apache.axis2.transport.http.util.HTTPProxyConfigurationUtil.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. Proxy settings can be get from * axis2.xml, Java proxy settings or can be override through property in message context. * <p/>/* w ww. j a v a2s.c o m*/ * HTTP Proxy setting element format: * <parameter name="Proxy"> * <Configuration> * <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> * <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> * <Configuration> * <parameter> * * @param messageContext in message context for * @param httpClient commons-httpclient instance * @param config commons-httpclient HostConfiguration * @throws AxisFault if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; //Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); } } // If there is runtime proxy settings, these settings will override settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.cocoon.generation.WebServiceProxyGenerator.java
/** * Create one per client session. /*from w w w . j a va2 s. co m*/ */ protected HttpClient getHttpClient() throws ProcessingException { URI uri = null; String host = null; Request request = ObjectModelHelper.getRequest(objectModel); Session session = request.getSession(true); HttpClient httpClient = null; if (session != null) { httpClient = (HttpClient) session.getAttribute(HTTP_CLIENT); } if (httpClient == null) { httpClient = new HttpClient(); HostConfiguration config = httpClient.getHostConfiguration(); if (config == null) { config = new HostConfiguration(); } /* TODO: fixme! * When the specified source sent to the wsproxy is not "http" * (e.g. "cocoon:/"), the HttpClient throws an exception. Does the source * here need to be resolved before being set in the HostConfiguration? */ try { uri = new URI(this.source); host = uri.getHost(); config.setHost(uri); } catch (URIException ex) { throw new ProcessingException("URI format error: " + ex, ex); } // Check the http.nonProxyHosts to see whether or not the current // host needs to be served through the proxy server. boolean proxiableHost = true; String nonProxyHosts = System.getProperty("http.nonProxyHosts"); if (nonProxyHosts != null) { StringTokenizer tok = new StringTokenizer(nonProxyHosts, "|"); while (tok.hasMoreTokens()) { String nonProxiableHost = tok.nextToken().trim(); // XXX is there any other characters that need to be // escaped? nonProxiableHost = StringUtils.replace(nonProxiableHost, ".", "\\."); nonProxiableHost = StringUtils.replace(nonProxiableHost, "*", ".*"); // XXX do we want .example.com to match // computer.example.com? it seems to be a very common // idiom for the nonProxyHosts, in that case then we want // to change "^" to "^.*" RE re = null; try { re = new RE("^" + nonProxiableHost + "$"); } catch (Exception ex) { throw new ProcessingException("Regex syntax error: " + ex, ex); } if (re.match(host)) { proxiableHost = false; break; } } } if (proxiableHost && System.getProperty("http.proxyHost") != null) { String proxyHost = System.getProperty("http.proxyHost"); int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort")); config.setProxy(proxyHost, proxyPort); } httpClient.setHostConfiguration(config); session.setAttribute(HTTP_CLIENT, httpClient); } return httpClient; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }// ww w . j a v a 2 s . c o m nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
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>/*from ww w . j a v a 2 s . c o m*/ * 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.apache.maven.doxia.linkcheck.validation.OnlineHTTPLinkValidator.java
/** Initialize the HttpClient. */ private void initHttpClient() { LOG.debug("A new HttpClient instance is needed ..."); this.cl = new HttpClient(new MultiThreadedHttpConnectionManager()); // Default params if (this.http.getTimeout() != 0) { this.cl.getHttpConnectionManager().getParams().setConnectionTimeout(this.http.getTimeout()); this.cl.getHttpConnectionManager().getParams().setSoTimeout(this.http.getTimeout()); }/*from ww w . j a v a 2 s . com*/ this.cl.getParams().setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); HostConfiguration hc = new HostConfiguration(); HttpState state = new HttpState(); if (StringUtils.isNotEmpty(this.http.getProxyHost())) { hc.setProxy(this.http.getProxyHost(), this.http.getProxyPort()); if (LOG.isDebugEnabled()) { LOG.debug("Proxy Host:" + this.http.getProxyHost()); LOG.debug("Proxy Port:" + this.http.getProxyPort()); } if (StringUtils.isNotEmpty(this.http.getProxyUser()) && this.http.getProxyPassword() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Proxy User:" + this.http.getProxyUser()); } Credentials credentials; if (StringUtils.isNotEmpty(this.http.getProxyNtlmHost())) { credentials = new NTCredentials(this.http.getProxyUser(), this.http.getProxyPassword(), this.http.getProxyNtlmHost(), this.http.getProxyNtlmDomain()); } else { credentials = new UsernamePasswordCredentials(this.http.getProxyUser(), this.http.getProxyPassword()); } state.setProxyCredentials(AuthScope.ANY, credentials); } } else { LOG.debug("Not using a proxy"); } this.cl.setHostConfiguration(hc); this.cl.setState(state); LOG.debug("New HttpClient instance created."); }
From source file:org.apache.maven.proxy.config.HttpRepoConfiguration.java
private HttpClient createHttpClient() { HttpClient client = new HttpClient(); HostConfiguration hostConf = new HostConfiguration(); ProxyConfiguration proxy = getProxy(); if (proxy != null) { hostConf.setProxy(proxy.getHost(), proxy.getPort()); client.setHostConfiguration(hostConf); if (proxy.getUsername() != null) { Credentials creds = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); client.getState().setProxyCredentials(null, null, creds); }//w w w. ja va 2 s. c om } return client; }
From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagon.java
public void openConnectionInternal() { repository.setUrl(getURL(repository)); client = new HttpClient(connectionManager); // WAGON-273: default the cookie-policy to browser compatible client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); String username = null;/*from w ww . j a v a 2 s . com*/ String password = null; String domain = null; if (authenticationInfo != null) { username = authenticationInfo.getUserName(); if (StringUtils.contains(username, "\\")) { String[] domainAndUsername = username.split("\\\\"); domain = domainAndUsername[0]; username = domainAndUsername[1]; } password = authenticationInfo.getPassword(); } String host = getRepository().getHost(); if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { Credentials creds; if (domain != null) { creds = new NTCredentials(username, password, host, domain); } else { creds = new UsernamePasswordCredentials(username, password); } int port = getRepository().getPort() > -1 ? getRepository().getPort() : AuthScope.ANY_PORT; AuthScope scope = new AuthScope(host, port); client.getState().setCredentials(scope, creds); } HostConfiguration hc = new HostConfiguration(); ProxyInfo proxyInfo = getProxyInfo(getRepository().getProtocol(), getRepository().getHost()); if (proxyInfo != null) { String proxyUsername = proxyInfo.getUserName(); String proxyPassword = proxyInfo.getPassword(); String proxyHost = proxyInfo.getHost(); int proxyPort = proxyInfo.getPort(); String proxyNtlmHost = proxyInfo.getNtlmHost(); String proxyNtlmDomain = proxyInfo.getNtlmDomain(); if (proxyHost != null) { hc.setProxy(proxyHost, proxyPort); if (proxyUsername != null && proxyPassword != null) { Credentials creds; if (proxyNtlmHost != null || proxyNtlmDomain != null) { creds = new NTCredentials(proxyUsername, proxyPassword, proxyNtlmHost, proxyNtlmDomain); } else { creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword); } int port = proxyInfo.getPort() > -1 ? proxyInfo.getPort() : AuthScope.ANY_PORT; AuthScope scope = new AuthScope(proxyHost, port); client.getState().setProxyCredentials(scope, creds); } } } hc.setHost(host); //start a session with the webserver client.setHostConfiguration(hc); }