List of usage examples for org.apache.commons.httpclient HostConfiguration setProxy
public void setProxy(String paramString, int paramInt)
From source file:Correct.java
public static void main(String[] args) { String URLL = ""; HttpClient client = new HttpClient(); HttpMethod method = new PostMethod(URLL); method.setDoAuthentication(true);/* w w w . j a va2 s . c om*/ HostConfiguration hostConfig = client.getHostConfiguration(); hostConfig.setHost("172.29.38.8"); hostConfig.setProxy("172.29.90.4", 8); // NTCredentials proxyCredentials = new NTCredentials("", "", "", ""); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", "")); //// try { //// URL url = new URL(""); //// HttpURLConnection urls = (HttpURLConnection) url.openConnection(); //// //// //// } catch (MalformedURLException ex) { //// Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex); //// } catch (IOException ex) { //// Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex); //// } try { // send the transaction client.executeMethod(hostConfig, method); StatusLine status = method.getStatusLine(); if (status != null && method.getStatusCode() == 200) { System.out.println(method.getResponseBodyAsString() + "\n Status code : " + status); } else { System.err.println(method.getStatusLine() + "\n: Posting Failed !"); } } catch (IOException ioe) { ioe.printStackTrace(); } method.releaseConnection(); }
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void main(String[] args) { // test();//from ww w .j a va 2s . c o m // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP // System.setProperty("proxyPort", "8080"); // System.setProperty("socksProxyPort", "1080"); // // Authenticator.setDefault(new MyAuthenticator()); // Create an instance of HttpClient. // HttpClient client = new HttpClient(); HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager()); // Create a method instance. GetMethod method = new GetMethod(url); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setProxy("proxy.cls.fr", 8080); client.setHostConfiguration(hostConfiguration); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // String username = "xxx"; // String password = "xxx"; // Credentials credentials = new UsernamePasswordCredentials(username, password); // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080); // // client.getState().setProxyCredentials(authScope, credentials); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:fr.gouv.finances.dgfip.xemelios.common.NetAccess.java
public static HttpClient getHttpClient(PropertiesExpansion applicationProperties) throws DataConfigurationException { String proxyHost = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_SERVER); String proxyPort = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PORT); String proxyUser = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_USER); String sTmp = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PASSWD); String proxyPasswd = sTmp != null ? Scramble.unScramblePassword(sTmp) : null; int intProxyPort = 0; if (proxyPort != null) { try {/*from w ww . j a va 2s. c om*/ intProxyPort = Integer.parseInt(proxyPort); } catch (NumberFormatException nfEx) { throw new DataConfigurationException(proxyPort + " n'est pas un numro de port valide."); } } String domainName = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_DOMAIN); HttpClient client = new HttpClient(); //client.getParams().setAuthenticationPreemptive(true); // check use of this HostConfiguration hc = new HostConfiguration(); if (proxyHost != null) { hc.setProxy(proxyHost, intProxyPort); client.setHostConfiguration(hc); } if (proxyUser != null) { Credentials creds = null; if (domainName != null && domainName.length() > 0) { String hostName = "127.0.0.1"; try { InetAddress ip = InetAddress.getByName("127.0.0.1"); hostName = ip.getHostName(); } catch (Exception ex) { logger.error("", ex); } creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName); } else { creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd); } client.getState().setProxyCredentials(AuthScope.ANY, creds); // client.getState().setProxyCredentials(AuthScope.ANY,new UsernamePasswordCredentials(proxyUser,proxyPasswd)); } return client; }
From source file:com.worldline.easycukes.commons.Configuration.java
/** * Allows to deal with the proxy configuration. It creates a * {@link HostConfiguration} object that can be used by the HTTPClient, and * also sets the proxy in system variables. * * @return a {@link HostConfiguration} containing information about the * proxy, along with the fact that system properties have been set. * Null if the proxy is not specified *///from w w w. ja v a2 s . c om public static HostConfiguration configureProxy() { if (!isLoaded) load(); if (isProxyNeeded()) { LOGGER.info("Proxy is needed => configuring the http client"); final HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setProxy( environment.get("proxy").get("host") != null ? environment.get("proxy").get("host").toString() : "", environment.get("proxy").get("port") != null ? Integer.parseInt(environment.get("proxy").get("port").toString()) : 0); LOGGER.info("Setting the proxy... Using " + hostConfiguration.getProxyHost() + ":" + hostConfiguration.getProxyPort()); // Set system properties too System.setProperty("https.proxyHost", environment.get("proxy").get("host").toString()); System.setProperty("https.proxyPort", environment.get("proxy").get("port").toString()); return hostConfiguration; } return null; }
From source file:de.mpg.imeji.presentation.util.ProxyHelper.java
/** * check if proxy has to get used for given url. * If yes, set ProxyHost in httpClient//from w w w .jav a 2 s .co m * * @param url url * * @throws Exception */ public static void setProxy(final HttpClient httpClient, final String url) { getProxyProperties(); if (proxyHost != null) { org.apache.commons.httpclient.HostConfiguration hc = httpClient.getHostConfiguration(); if (findUrlInNonProxyHosts(url)) { hc.setProxyHost(null); } else { hc.setProxy(proxyHost, Integer.valueOf(proxyPort)); } } }
From source file:de.mpg.escidoc.services.common.util.ProxyHelper.java
/** * check if proxy has to get used for given url. * If yes, set ProxyHost in httpClient//from w w w . ja va 2 s . c o m * * @param url url * * @throws Exception */ public static void setProxy(final HttpClient httpClient, final String url) { getProxyProperties(); if (proxyHost != null) { HostConfiguration hc = httpClient.getHostConfiguration(); if (findUrlInNonProxyHosts(url)) { hc.setProxyHost(null); } else { hc.setProxy(proxyHost, Integer.valueOf(proxyPort)); } } }
From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java
public static Cookie[] validateFromCAS2(String username, String password) throws Exception { String url = casServerUrlPrefix + "/v1/tickets?"; String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8"); s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8"); HttpState initialState = new HttpState(); // Initial set of cookies can be retrieved from persistent storage and // re-created, using a persistence mechanism of choice, // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false); // Create an instance of HttpClient. // HttpClient client = new HttpClient(); HttpClient client = new HttpClient(); Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443); URI uri = new URI(url + s, true); // use relative url only PostMethod httpget = new PostMethod(url); httpget.addParameter("username", username); httpget.addParameter("password", password); HostConfiguration hc = new HostConfiguration(); hc.setHost("atoll-dev.cls.fr", 8443, easyhttps); // client.executeMethod(hc, httpget); client.setState(initialState);/*from w ww. j ava 2 s. co m*/ // Create a method instance. System.out.println(url + s); GetMethod method = new GetMethod(url + s); // GetMethod method = new GetMethod(url ); HostConfiguration hostConfiguration = new HostConfiguration(); hostConfiguration.setProxy("proxy.cls.fr", 8080); client.setHostConfiguration(hostConfiguration); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // String username = "xxx"; // String password = "xxx"; // Credentials credentials = new UsernamePasswordCredentials(username, password); // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080); // // client.getState().setProxyCredentials(authScope, credentials); Cookie[] cookies = null; try { // Execute the method. // int statusCode = client.executeMethod(method); int statusCode = client.executeMethod(hc, httpget); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } for (Header header : method.getRequestHeaders()) { System.out.println(header.getName()); System.out.println(header.getValue()); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data System.out.println(new String(responseBody)); System.out.println("Response status code: " + statusCode); // Get all the cookies cookies = client.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } Assertion assertion = AssertionHolder.getAssertion(); if (assertion == null) { System.out.println("<p>Assertion is null</p>"); } } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return cookies; }
From source file:com.feilong.tools.net.httpclient3.HttpClientUtil.java
/** * proxy.//from w w w. j a v a2 s .c om * * @param httpClientConfig * the http client config * @param httpClient * the http client */ // TODO private static void setProxy(HttpClientConfig httpClientConfig, HttpClient httpClient) { // ? String hostName = httpClientConfig.getProxyAddress(); if (Validator.isNotNullOrEmpty(hostName)) { int port = httpClientConfig.getProxyPort(); HostConfiguration hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setProxy(hostName, port); } }
From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java
private static void setProxy(HostConfiguration config, HttpState state, ProxyData data) { // set Proxy//from ww w.j a v a 2s. com if (ProxyDataImpl.isValid(data)) { config.setProxy(data.getServer(), data.getPort() <= 0 ? 80 : data.getPort()); if (ProxyDataImpl.hasCredentials(data)) { state.setProxyCredentials(null, null, new UsernamePasswordCredentials(data.getUsername(), StringUtil.emptyIfNull(data.getPassword()))); } } }
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 ww.j a va 2 s.c o m*/ * @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; }