List of usage examples for org.apache.commons.httpclient HttpClient setState
public void setState(HttpState paramHttpState)
From source file:CookieDemoApp.java
/** * * Usage://from w w w. j a v a2 s.c o m * java CookieDemoApp http://mywebserver:80/ * * @param args command line arguments * Argument 0 is a URL to a web server * * */ public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java CookieDemoApp <url>"); System.err.println("<url> The url of a webpage"); System.exit(1); } // Get target URL String strURL = args[0]; System.out.println("Target URL: " + strURL); // Get initial state object 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); // and then added to your HTTP state instance initialState.addCookie(mycookie); // Get HTTP client instance HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); httpclient.setState(initialState); // RFC 2101 cookie management spec is used per default // to parse, validate, format & match cookies httpclient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); // A different cookie management spec can be selected // when desired //httpclient.getParams().setCookiePolicy(CookiePolicy.NETSCAPE); // Netscape Cookie Draft spec is provided for completeness // You would hardly want to use this spec in real life situations //httppclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // Compatibility policy is provided in order to mimic cookie // management of popular web browsers that is in some areas // not 100% standards compliant // Get HTTP GET method GetMethod httpget = new GetMethod(strURL); // Execute HTTP GET int result = httpclient.executeMethod(httpget); // Display status code System.out.println("Response status code: " + result); // Get all the cookies Cookie[] cookies = httpclient.getState().getCookies(); // Display the cookies System.out.println("Present cookies: "); for (int i = 0; i < cookies.length; i++) { System.out.println(" - " + cookies[i].toExternalForm()); } // Release current connection to the connection pool once you are done httpget.releaseConnection(); }
From source file:com.zimbra.cs.servlet.ZimbraServlet.java
public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, HttpMethod method, HttpState state) throws IOException, ServiceException { // create an HTTP client with the same cookies javax.servlet.http.Cookie cookies[] = req.getCookies(); String hostname = method.getURI().getHost(); boolean hasZMAuth = hasZimbraAuthCookie(state); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(ZimbraCookie.COOKIE_ZM_AUTH_TOKEN) && hasZMAuth) continue; state.addCookie(/*from w ww .j a v a 2 s . c o m*/ new Cookie(hostname, cookies[i].getName(), cookies[i].getValue(), "/", null, false)); } } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); if (state != null) client.setState(state); int hopcount = 0; for (Enumeration<?> enm = req.getHeaderNames(); enm.hasMoreElements();) { String hname = (String) enm.nextElement(), hlc = hname.toLowerCase(); if (hlc.equals("x-zimbra-hopcount")) try { hopcount = Math.max(Integer.parseInt(req.getHeader(hname)), 0); } catch (NumberFormatException e) { } else if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.equals("authorization")) method.addRequestHeader(hname, req.getHeader(hname)); } if (hopcount >= MAX_PROXY_HOPCOUNT) throw ServiceException.TOO_MANY_HOPS(HttpUtil.getFullRequestURL(req)); method.addRequestHeader("X-Zimbra-Hopcount", Integer.toString(hopcount + 1)); if (method.getRequestHeader("X-Zimbra-Orig-Url") == null) method.addRequestHeader("X-Zimbra-Orig-Url", req.getRequestURL().toString()); String ua = req.getHeader("User-Agent"); if (ua != null) method.setRequestHeader("User-Agent", ua); // dispatch the request and copy over the results int statusCode = -1; for (int retryCount = 3; statusCode == -1 && retryCount > 0; retryCount--) { statusCode = HttpClientUtil.executeMethod(client, method); } if (statusCode == -1) { resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "retry limit reached"); return; } else if (statusCode >= 300) { resp.sendError(statusCode, method.getStatusText()); return; } Header[] headers = method.getResponseHeaders(); for (int i = 0; i < headers.length; i++) { String hname = headers[i].getName(), hlc = hname.toLowerCase(); if (hlc.startsWith("x-") || hlc.startsWith("content-") || hlc.startsWith("www-")) resp.addHeader(hname, headers[i].getValue()); } InputStream responseStream = method.getResponseBodyAsStream(); if (responseStream == null || resp.getOutputStream() == null) return; ByteUtil.copy(method.getResponseBodyAsStream(), false, resp.getOutputStream(), false); }
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); // Create a method instance. System.out.println(url + s);/*w w w . j a va 2 s. c o m*/ 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.zimbra.cs.util.SpamExtract.java
private static void extract(String authToken, Account account, Server server, String query, File outdir, boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException { String soapURL = getSoapURL(server, false); URL restURL = getServerURL(server, false); HttpClient hc = new HttpClient(); // CLI only, don't need conn mgr HttpState state = new HttpState(); GetMethod gm = new GetMethod(); gm.setFollowRedirects(true);/*from www . ja va2 s . c o m*/ Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1, false); state.addCookie(authCookie); hc.setState(state); hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(), Protocol.getProtocol(restURL.getProtocol())); gm.getParams().setSoTimeout(60000); if (verbose) { LOG.info("Mailbox requests to: " + restURL); } SoapHttpTransport transport = new SoapHttpTransport(soapURL); transport.setRetryCount(1); transport.setTimeout(0); transport.setAuthToken(authToken); int totalProcessed = 0; boolean haveMore = true; int offset = 0; while (haveMore) { Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST); searchReq.addElement(MailConstants.A_QUERY).setText(query); searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString()); searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset); searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE); try { if (LOG.isDebugEnabled()) { LOG.debug(searchReq.prettyPrint()); } Element searchResp = transport.invoke(searchReq, false, true, account.getId()); if (LOG.isDebugEnabled()) { LOG.debug(searchResp.prettyPrint()); } StringBuilder deleteList = new StringBuilder(); List<String> ids = new ArrayList<String>(); for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext();) { offset++; Element e = iter.next(); String mid = e.getAttribute(MailConstants.A_ID); if (mid == null) { LOG.warn("null message id SOAP response"); continue; } LOG.debug("adding id %s", mid); ids.add(mid); if (ids.size() >= BATCH_SIZE || !iter.hasNext()) { StringBuilder path = new StringBuilder("/service/user/" + account.getName() + "/?fmt=tgz&list=" + StringUtils.join(ids, ",")); LOG.debug("sending request for path %s", path.toString()); List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw); if (ids.size() > extractedIds.size()) { ids.removeAll(extractedIds); LOG.warn("failed to extract %s", ids); } for (String id : extractedIds) { deleteList.append(id).append(','); } ids.clear(); } totalProcessed++; } haveMore = false; String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE); if (more != null && more.length() > 0) { try { int m = Integer.parseInt(more); if (m > 0) { haveMore = true; try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { } } } catch (NumberFormatException nfe) { LOG.warn("more flag from server not a number: " + more, nfe); } } if (delete && deleteList.length() > 0) { deleteList.deleteCharAt(deleteList.length() - 1); // -1 removes trailing comma Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST); Element action = msgActionReq.addElement(MailConstants.E_ACTION); action.addAttribute(MailConstants.A_ID, deleteList.toString()); action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE); if (LOG.isDebugEnabled()) { LOG.debug(msgActionReq.prettyPrint()); } Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId()); if (LOG.isDebugEnabled()) { LOG.debug(msgActionResp.prettyPrint()); } offset = 0; //put offset back to 0 so we always get top N messages even after delete } } finally { gm.releaseConnection(); } } LOG.info("Total messages processed: " + totalProcessed); }
From source file:com.zimbra.qa.unittest.TestCollectConfigServletsAccess.java
/** * Verify that delegated admin canNOT access servlet at /service/collectconfig/ * @throws Exception//from w w w . j a v a2s.c o m */ @Test public void testConfigDelegatedAdmin() throws Exception { ZAuthToken at = TestUtil.getAdminSoapTransport(TEST_ADMIN_NAME, PASSWORD).getAuthToken(); URI servletURI = new URI(getConfigServletUrl()); HttpState initialState = HttpClientUtil.newHttpState(at, servletURI.getHost(), true); HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); restClient.setState(initialState); restClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); GetMethod get = new GetMethod(servletURI.toString()); int statusCode = HttpClientUtil.executeMethod(restClient, get); assertEquals("This request should NOT succeed. Getting status code " + statusCode, HttpStatus.SC_UNAUTHORIZED, statusCode); }
From source file:com.zimbra.qa.unittest.TestCollectConfigServletsAccess.java
/** * Verify that delegated admin canNOT access servlet at /service/collectldapconfig/ * @throws Exception//ww w. ja v a 2 s . co m */ @Test public void testLDAPConfigDelegatedAdmin() throws Exception { ZAuthToken at = TestUtil.getAdminSoapTransport(TEST_ADMIN_NAME, PASSWORD).getAuthToken(); URI servletURI = new URI(getLDAPConfigServletUrl()); HttpState initialState = HttpClientUtil.newHttpState(at, servletURI.getHost(), true); HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); restClient.setState(initialState); restClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); GetMethod get = new GetMethod(servletURI.toString()); int statusCode = HttpClientUtil.executeMethod(restClient, get); assertEquals("This request should NOT succeed. Getting status code " + statusCode, HttpStatus.SC_UNAUTHORIZED, statusCode); }
From source file:com.zimbra.cs.service.admin.StatsImageServlet.java
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AuthToken authToken = getAdminAuthTokenFromCookie(req, resp); if (authToken == null) return;//from ww w . jav a2 s. c o m String imgName = null; InputStream is = null; boolean imgAvailable = true; boolean localServer = false; boolean systemWide = false; String serverAddr = ""; String noDefaultImg = req.getParameter("nodef"); boolean noDefault = false; if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) { noDefault = true; } String reqPath = req.getRequestURI(); try { //check if this is the logger host, otherwise proxy the request to the logger host String serviceHostname = Provisioning.getInstance().getLocalServer() .getAttr(Provisioning.A_zimbraServiceHostname); String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname); if (!serviceHostname.equalsIgnoreCase(logHost)) { StringBuffer url = new StringBuffer("https"); url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value()); url.append(reqPath); String queryStr = req.getQueryString(); if (queryStr != null) url.append('?').append(queryStr); // create an HTTP client with the same cookies HttpState state = new HttpState(); try { state.addCookie(new org.apache.commons.httpclient.Cookie(logHost, ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false)); } catch (AuthTokenException ate) { throw ServiceException.PROXY_ERROR(ate, url.toString()); } HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); client.setState(state); GetMethod get = new GetMethod(url.toString()); try { int statusCode = HttpClientUtil.executeMethod(client, get); if (statusCode != HttpStatus.SC_OK) throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null); resp.setContentType("image/gif"); ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false); return; } catch (HttpException e) { throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e); } catch (IOException e) { throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e); } finally { get.releaseConnection(); } } } catch (Exception ex) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found"); return; } try { if (reqPath == null || reqPath.length() == 0) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (mLog.isDebugEnabled()) mLog.debug("received request to:(" + reqPath + ")"); String reqParts[] = reqPath.split("/"); String reqFilename = reqParts[3]; imgName = LC.stats_img_folder.value() + File.separator + reqFilename; try { is = new FileInputStream(imgName); } catch (FileNotFoundException ex) {//unlikely case - only if the server's files are broken if (is != null) is.close(); if (!noDefault) { imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL; is = new FileInputStream(imgName); } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found"); return; } } } catch (Exception ex) { if (is != null) is.close(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found"); return; } resp.setContentType("image/gif"); ByteUtil.copy(is, true, resp.getOutputStream(), false); }
From source file:com.twinsoft.convertigo.engine.billing.GoogleAnalyticsTicketManager.java
private HttpClient prepareHttpClient(String[] url) throws EngineException, MalformedURLException { final Pattern scheme_host_pattern = Pattern.compile("https://(.*?)(?::([\\d]*))?(/.*|$)"); 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 . ja v a2 s.com*/ 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.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 .j a v a 2 s.co m*/ 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; }