List of usage examples for org.apache.commons.httpclient HttpClient setHostConfiguration
public void setHostConfiguration(HostConfiguration paramHostConfiguration)
From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java
public static void main(String[] args) { // test();/*from w ww. j av a 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 ww w . java 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.liferay.util.Http.java
public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException { byte[] byteArray = null; HttpMethod method = null;//w w w. j ava2 s .c om try { HttpClient client = new HttpClient(new SimpleHttpConnectionManager()); if (location == null) { return byteArray; } else if (!location.startsWith(HTTP_WITH_SLASH) && !location.startsWith(HTTPS_WITH_SLASH)) { location = HTTP_WITH_SLASH + location; } HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(new URI(location)); if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) { hostConfig.setProxy(PROXY_HOST, PROXY_PORT); } client.setHostConfiguration(hostConfig); client.setConnectionTimeout(5000); client.setTimeout(5000); if (cookies != null && cookies.length > 0) { HttpState state = new HttpState(); state.addCookies(cookies); state.setCookiePolicy(CookiePolicy.COMPATIBILITY); client.setState(state); } if (post) { method = new PostMethod(location); } else { method = new GetMethod(location); } method.setFollowRedirects(true); client.executeMethod(method); Header locationHeader = method.getResponseHeader("location"); if (locationHeader != null) { return URLtoByteArray(locationHeader.getValue(), cookies, post); } InputStream is = method.getResponseBodyAsStream(); if (is != null) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] bytes = new byte[512]; for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) { buffer.write(bytes, 0, i); } byteArray = buffer.toByteArray(); is.close(); buffer.close(); } return byteArray; } finally { try { if (method != null) { method.releaseConnection(); } } catch (Exception e) { Logger.error(Http.class, e.getMessage(), e); } } }
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 av a 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.trunghoang.teammedical.utils.FileDownloader.java
public File urlDownloader(String downloadLocation) throws Exception { URL downloadURL = new URL(downloadLocation); HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort())); client.getParams().makeLenient();/*ww w .ja v a 2 s . co m*/ client.setState(mimicCookieState(driver.manage().getCookies())); HttpMethod getRequest = new GetMethod(downloadLocation); getRequest.setFollowRedirects(true); FileHandler downloadedFile = new FileHandler( downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true); try { int status = client.executeMethod(getRequest); log.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm()); downloadedFile.getWritableFileOutputStream().write(getRequest.getResponseBody()); downloadedFile.close(); log.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile()); } catch (Exception Ex) { log.error("Download failed: {}", Ex); throw new Exception("Download failed!"); } finally { getRequest.releaseConnection(); } return downloadedFile.getFile(); }
From source file:edu.tsinghua.lumaqq.test.CustomHeadUploader.java
/** * //from w w w . j a v a2s .c o m * * @param filename */ public void upload(String filename, QQUser user) { HttpClient client = new HttpClient(); HostConfiguration conf = new HostConfiguration(); conf.setHost(QQ.QQ_SERVER_UPLOAD_CUSTOM_HEAD); client.setHostConfiguration(conf); PostMethod method = new PostMethod("/cgi-bin/cface/upload"); method.addRequestHeader("Accept", "*/*"); method.addRequestHeader("Pragma", "no-cache"); StringPart uid = new StringPart("clientuin", String.valueOf(user.getQQ())); uid.setContentType(null); uid.setTransferEncoding(null); //StringPart clientkey = new StringPart("clientkey", "0D649E66B0C1DBBDB522CE9C846754EF6AFA10BBF1A48A532DF6369BBCEF6EE7"); //StringPart clientkey = new StringPart("clientkey", "3285284145CC19EC0FFB3B25E4F6817FF3818B0E72F1C4E017D9238053BA2040"); StringPart clientkey = new StringPart("clientkey", "2FEEBE858DAEDFE6352870E32E5297ABBFC8C87125F198A5232FA7ADA9EADE67"); //StringPart clientkey = new StringPart("clientkey", "8FD643A7913C785AB612F126C6CD68A253F459B90EBCFD9375053C159418AF16"); // StringPart clientkey = new StringPart("clientkey", Util.convertByteToHexStringWithoutSpace(user.getClientKey())); clientkey.setContentType(null); clientkey.setTransferEncoding(null); //StringPart sign = new StringPart("sign", "2D139466226299A73F8BCDA7EE9AB157E8D9DA0BB38B6F4942A1658A00BD4C1FEE415838810E5AEF40B90E2AA384A875"); //StringPart sign = new StringPart("sign", "50F479417088F26EFC75B9BCCF945F35346188BB9ADD3BDF82098C9881DA086E3B28D56726D6CB2331909B62459E1E62"); //StringPart sign = new StringPart("sign", "31A69198C19A7C4BFB60DCE352FE2CC92C9D27E7C7FEADE1CBAAFD988906981ECC0DD1782CBAE88A2B716F84F9E285AA"); StringPart sign = new StringPart("sign", "68FFB636DE63D164D4072D7581213C77EC7B425DDFEB155428768E1E409935AA688AC88910A74C5D2D94D5EF2A3D1764"); sign.setContentType(null); sign.setTransferEncoding(null); FilePart file; try { file = new FilePart("customfacefile", filename, new File(filename)); } catch (FileNotFoundException e) { return; } Part[] parts = new Part[] { uid, clientkey, sign, file }; MultipartRequestEntity entity = new MultipartRequestEntity(parts, method.getParams()); method.setRequestEntity(entity); try { client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { Header header = method.getResponseHeader("CFace-Msg"); System.out.println(header.getValue()); header = method.getResponseHeader("CFace-RetCode"); System.out.println(header.getValue()); } } catch (HttpException e) { return; } catch (IOException e) { return; } finally { method.releaseConnection(); } }
From source file:com.lazerycode.ebselen.customhandlers.FileDownloader.java
public String downloader(WebElement element, String attribute) throws Exception { //Assuming that getAttribute does some magic to return a fully qualified URL String downloadLocation = element.getAttribute(attribute); if (downloadLocation.trim().equals("")) { throw new Exception("The element you have specified does not link to anything!"); }//from w w w .jav a2 s. c om URL downloadURL = new URL(downloadLocation); HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort())); client.setState(mimicCookieState(driver.manage().getCookies())); HttpMethod getRequest = new GetMethod(downloadURL.getPath()); FileHandler downloadedFile = new FileHandler( downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""), true); try { int status = client.executeMethod(getRequest); LOGGER.info("HTTP Status {} when getting '{}'", status, downloadURL.toExternalForm()); BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream()); int offset = 0; int len = 4096; int bytes = 0; byte[] block = new byte[len]; while ((bytes = in.read(block, offset, len)) > -1) { downloadedFile.getWritableFileOutputStream().write(block, 0, bytes); } downloadedFile.close(); in.close(); LOGGER.info("File downloaded to '{}'", downloadedFile.getAbsoluteFile()); } catch (Exception Ex) { LOGGER.error("Download failed: {}", Ex); throw new Exception("Download failed!"); } finally { getRequest.releaseConnection(); } return downloadedFile.getAbsoluteFile(); }
From source file:jhc.redsniff.webdriver.download.FileDownloader.java
private HttpClient createHttpClient(URL downloadURL) { HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort())); client.setState(mimicCookieState(driver.manage().getCookies())); return client; }
From source file:com.testmax.util.FileDownLoader.java
public String downloader(WebElement element, String attribute) throws Exception { //Assuming that getAttribute does some magic to return a fully qualified URL String downloadLocation = element.getAttribute(attribute); if (downloadLocation.trim().equals("")) { throw new Exception("The element you have specified does not link to anything!"); }//from w ww . ja va 2s . c o m URL downloadURL = new URL(downloadLocation); HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setHostConfiguration(mimicHostConfiguration(downloadURL.getHost(), downloadURL.getPort())); client.setState(mimicCookieState(driver.manage().getCookies())); HttpMethod getRequest = new GetMethod(downloadURL.getPath()); String file_path = downloadPath + downloadURL.getFile().replaceFirst("/|\\\\", ""); FileWriter downloadedFile = new FileWriter(file_path, true); try { int status = client.executeMethod(getRequest); WmLog.getCoreLogger().info("HTTP Status {} when getting '{}'" + status + downloadURL.toExternalForm()); BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream()); int offset = 0; int len = 4096; int bytes = 0; byte[] block = new byte[len]; while ((bytes = in.read(block, offset, len)) > -1) { downloadedFile.write(bytes); } downloadedFile.close(); in.close(); WmLog.getCoreLogger().info("File downloaded to '{}'" + file_path); } catch (Exception Ex) { WmLog.getCoreLogger().error("Download failed: {}", Ex); throw new Exception("Download failed!"); } finally { getRequest.releaseConnection(); } return file_path; }
From source file:com.predic8.membrane.integration.AccessControlInterceptorIntegrationTest.java
private HttpClient getClient(byte[] ip) throws UnknownHostException { HttpClient client = new HttpClient(); HostConfiguration config = new HostConfiguration(); config.setLocalAddress(InetAddress.getByAddress(ip)); client.setHostConfiguration(config); return client; }