List of usage examples for org.apache.commons.httpclient HttpClient setState
public void setState(HttpState paramHttpState)
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!"); }/* w w w .j a v a 2 s.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.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 a v a 2 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: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();//from ww w . j av 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:de.suse.swamp.core.util.BugzillaTools.java
private Cookie[] bzConnect(String username, String pwd) throws Exception { Logger.DEBUG("Performing bugzilla login..."); HttpState initialState = new HttpState(); // Do a Login at Bugzilla HttpClient httpclient = new HttpClient(); httpclient.setState(initialState); String loginUrl = swamp.getProperty("BUGZILLA_LOGIN_URL"); // add form fields for logging in: String usernameField = swamp.getProperty("BUGZILLA_LOGIN_FORM_USERNAME"); String passwordField = swamp.getProperty("BUGZILLA_LOGIN_FORM_PWD"); NameValuePair login = new NameValuePair(usernameField, username); NameValuePair pw = new NameValuePair(passwordField, pwd); NameValuePair loginid = new NameValuePair("GoAheadAndLogIn", "1"); PostMethod httppost = new PostMethod(loginUrl); httppost.setRequestBody(new NameValuePair[] { login, pw, loginid }); try {/*from ww w . jav a 2 s.com*/ httpclient.executeMethod(httppost); } catch (Exception e) { throw new Exception("Could not connect to " + loginUrl + " (error: " + e.getMessage() + ")"); } Cookie[] cookies = httpclient.getState().getCookies(); //System.out.println("Response: " + httppost.getResponseBodyAsString()); if (cookies == null || cookies.length == 0) { throw new Exception("Could not login to " + loginUrl); } httppost.releaseConnection(); return cookies; }
From source file:de.suse.swamp.core.util.BugzillaTools.java
private synchronized void xmlToData(String url) throws Exception { HttpState initialState = new HttpState(); String authUsername = swamp.getProperty("BUGZILLA_AUTH_USERNAME"); String authPassword = swamp.getProperty("BUGZILLA_AUTH_PWD"); if (authUsername != null && authUsername.length() != 0) { Credentials defaultcreds = new UsernamePasswordCredentials(authUsername, authPassword); initialState.setCredentials(AuthScope.ANY, defaultcreds); } else {/* w w w .j a v a 2 s . c om*/ Cookie[] cookies = getCookies(); for (int i = 0; i < cookies.length; i++) { initialState.addCookie(cookies[i]); Logger.DEBUG("Added Cookie: " + cookies[i].getName() + "=" + cookies[i].getValue(), log); } } HttpClient httpclient = new HttpClient(); httpclient.setState(initialState); HttpMethod httpget = new GetMethod(url); try { httpclient.executeMethod(httpget); } catch (Exception e) { throw new Exception("Could not get URL " + url); } String content = httpget.getResponseBodyAsString(); char[] chars = content.toCharArray(); // removing illegal characters from bugzilla output. for (int i = 0; i < chars.length; i++) { if (chars[i] < 32 && chars[i] != 9 && chars[i] != 10 && chars[i] != 13) { Logger.DEBUG("Removing illegal character: '" + chars[i] + "' on position " + i, log); chars[i] = ' '; } } Logger.DEBUG(String.valueOf(chars), log); CharArrayReader reader = new CharArrayReader(chars); XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); parser.setFeature("http://xml.org/sax/features/validation", false); // disable parsing of external dtd parser.setFeature("http://xml.org/sax/features/external-general-entities", false); parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false); parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); // get XML File BugzillaReader handler = new BugzillaReader(); parser.setContentHandler(handler); InputSource source = new InputSource(); source.setCharacterStream(reader); source.setEncoding("utf-8"); try { parser.parse(source); } catch (SAXParseException spe) { spe.printStackTrace(); throw spe; } httpget.releaseConnection(); if (errormsg != null) { throw new Exception(errormsg); } }
From source file:com.zimbra.qa.unittest.TestAccessKeyGrant.java
public void testCalendarGet_guest() throws Exception { HttpState initialState = new HttpState(); /*//www . j a v a 2 s . c o m Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false); Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false); initialState.addCookie(authCookie); initialState.addCookie(sessionCookie); */ String guestName = "g1@guest.com"; String guestPassword = "zzz"; Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword); initialState.setCredentials(AuthScope.ANY, loginCredentials); HttpClient client = new HttpClient(); client.setState(initialState); String url = getRestCalendarUrl(OWNER_NAME); System.out.println("REST URL: " + url); HttpMethod method = new GetMethod(url); executeHttpMethod(client, method); }
From source file:arena.httpclient.commons.JakartaCommonsHttpClient.java
public HttpResponse get() throws IOException { NameValuePair params[] = new NameValuePair[0]; if (this.requestParameters != null) { List<NameValuePair> paramList = new ArrayList<NameValuePair>(); for (String key : this.requestParameters.keySet()) { String[] multipleValues = this.requestParameters.get(key); for (String value : multipleValues) { paramList.add(new NameValuePair(key, value)); }/* w w w . j a va2 s. c o m*/ } params = paramList.toArray(new NameValuePair[paramList.size()]); } HttpMethod method = null; if (this.isPost) { method = new PostMethod(this.url); if (this.encoding != null) { method.getParams().setContentCharset(this.encoding); } ((PostMethod) method).setRequestBody(params); } else { String url = this.url; for (int n = 0; n < params.length; n++) { url = URLUtils.addParamToURL(url, params[n].getName(), params[n].getValue(), this.encoding, false); } method = new GetMethod(url); method.setFollowRedirects(true); if (this.encoding != null) { method.getParams().setContentCharset(this.encoding); } } HttpClient client = new HttpClient(this.manager); if (this.connectTimeout != null) { client.getHttpConnectionManager().getParams().setConnectionTimeout(this.connectTimeout.intValue()); } if (this.readTimeout != null) { client.getHttpConnectionManager().getParams().setSoTimeout(this.readTimeout.intValue()); } client.setState(this.state); try { int statusCode = client.executeMethod(method); return new HttpResponse(getResponseBytes(method), statusCode, buildHeaderMap(method.getResponseHeaders())); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.zimbra.cs.service.UserServlet.java
private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method) throws ServiceException { // create an HTTP client with the same cookies String url = ""; String hostname = ""; try {//from w ww . ja va2 s . c o m url = method.getURI().toString(); hostname = method.getURI().getHost(); } catch (IOException e) { log.warn("can't parse target URI", e); } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); Map<String, String> cookieMap = authToken.cookieMap(false); if (cookieMap != null) { HttpState state = new HttpState(); for (Map.Entry<String, String> ck : cookieMap.entrySet()) { state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/", null, false)); } client.setState(state); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } if (method instanceof PutMethod) { long contentLength = ((PutMethod) method).getRequestEntity().getContentLength(); if (contentLength > 0) { int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis // cannot set connection time using our ZimbrahttpConnectionManager, // see comments in ZimbrahttpConnectionManager. // actually, length of the content to Put should not be a factor for // establishing a connection, only read time out matter, which we set // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate); method.getParams().setSoTimeout(timeEstimate); } } try { int statusCode = HttpClientUtil.executeMethod(client, method); if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN) throw MailServiceException.NO_SUCH_ITEM(-1); else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null, new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR), new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode, ServiceException.Argument.Type.NUM)); List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders())); headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode)); return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method); } catch (HttpException e) { throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e); } catch (IOException e) { throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e); } }
From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java
private HttpClient prepareHttpClient(String[] url) throws EngineException, MalformedURLException { HttpClient client = new HttpClient(); HostConfiguration hostConfiguration = client.getHostConfiguration(); HttpState httpState = new HttpState(); client.setState(httpState); if (proxyManager != null) { proxyManager.getEngineProperties(); proxyManager.setProxy(hostConfiguration, httpState, new URL(url[0])); }// w w w . j a v a 2 s .c o m Matcher matcher = scheme_host_pattern.matcher(url[0]); if (matcher.matches()) { String host = matcher.group(1); String sPort = matcher.group(2); int port = 443; try { port = Integer.parseInt(sPort); } catch (Exception e) { } try { Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(null, null, null, null, true), port); hostConfiguration.setHost(host, port, myhttps); url[0] = matcher.group(3); } catch (Exception e) { e.printStackTrace(); e.printStackTrace(); } } return client; }
From source file:com.zimbra.qa.unittest.TestFileUpload.java
@Test public void testMissingCsrfAdminUpload() throws Exception { SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl()); com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest( LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value()); req.setCsrfSupported(true);/*from www. j ava 2 s. com*/ Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory())); com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response); String authToken = authResp.getAuthToken(); int port = 7071; try { port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0); } catch (ServiceException e) { ZimbraLog.test.error("Unable to get admin SOAP port", e); } String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL; PostMethod post = new PostMethod(Url); FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes())); String contentType = "application/x-msdownload"; part.setContentType(contentType); HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); HttpState state = new HttpState(); state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false)); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.setState(state); post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams())); int statusCode = HttpClientUtil.executeMethod(client, post); assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode); String resp = post.getResponseBodyAsString(); assertNotNull("Response should not be empty", resp); assertTrue("Incorrect HTML response", resp.contains(RESP_STR)); }