List of usage examples for org.apache.commons.httpclient.cookie CookiePolicy getDefaultSpec
public static CookieSpec getDefaultSpec()
From source file:FormLoginDemo.java
public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the RFC2109 // We have to resort to using compatibility cookie policy GetMethod authget = new GetMethod("/servlet/SessionServlet"); client.executeMethod(authget);//from ww w.java 2s .c o m System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); if (initcookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < initcookies.length; i++) { System.out.println("- " + initcookies[i].toString()); } } PostMethod authpost = new PostMethod("/servlet/SessionServlet"); // Prepare login parameters NameValuePair action = new NameValuePair("action", "login"); NameValuePair url = new NameValuePair("url", "/index.html"); NameValuePair userid = new NameValuePair("UserId", "userid"); NameValuePair password = new NameValuePair("Password", "password"); authpost.setRequestBody(new NameValuePair[] { action, url, userid, password }); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:"); if (logoncookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < logoncookies.length; i++) { System.out.println("- " + logoncookies[i].toString()); } } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } System.out.println("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); System.out.println("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method redirect.releaseConnection(); } else { System.out.println("Invalid redirect"); System.exit(1); } } }
From source file:com.mytutorials.httpclient.FormLoginDemo.java
public static void main(String[] args) throws Exception { HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the // RFC2109//from w w w . j av a 2 s.c om // We have to resort to using compatibility cookie policy GetMethod authget = new GetMethod("/servlet/SessionServlet"); client.executeMethod(authget); System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); if (initcookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < initcookies.length; i++) { System.out.println("- " + initcookies[i].toString()); } } PostMethod authpost = new PostMethod("/servlet/SessionServlet"); // Prepare login parameters NameValuePair action = new NameValuePair("action", "login"); NameValuePair url = new NameValuePair("url", "/index.html"); NameValuePair userid = new NameValuePair("UserId", "userid"); NameValuePair password = new NameValuePair("Password", "password"); authpost.setRequestBody(new NameValuePair[] { action, url, userid, password }); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:"); if (logoncookies.length == 0) { System.out.println("None"); } else { for (int i = 0; i < logoncookies.length; i++) { System.out.println("- " + logoncookies[i].toString()); } } // Usually a successful form-based login results in a redicrect to // another url int statuscode = authpost.getStatusCode(); if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) { Header header = authpost.getResponseHeader("location"); if (header != null) { String newuri = header.getValue(); if ((newuri == null) || (newuri.equals(""))) { newuri = "/"; } System.out.println("Redirect target: " + newuri); GetMethod redirect = new GetMethod(newuri); client.executeMethod(redirect); System.out.println("Redirect: " + redirect.getStatusLine().toString()); // release any connection resources used by the method redirect.releaseConnection(); } else { System.out.println("Invalid redirect"); System.exit(1); } } }
From source file:com.djimenez.tuenti.example.FormLoginDemo.java
public static void main(final String[] args) throws Exception { final HttpClient client = new HttpClient(); client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // 'developer.java.sun.com' has cookie compliance problems // Their session cookie's domain attribute is in violation of the RFC2109 // We have to resort to using compatibility cookie policy final GetMethod authget = new GetMethod(LOGON_PATH); authget.setFollowRedirects(true);// ww w .j a v a 2 s .co m client.executeMethod(authget); System.out.println("Login form get: " + authget.getStatusLine().toString()); // release any connection resources used by the method authget.releaseConnection(); // See if we got any cookies final CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); final Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Initial set of cookies:"); checkCookies(initcookies); final PostMethod authpost = new PostMethod(LOGON_PATH); // Prepare login parameters final NameValuePair action = new NameValuePair("action", "do_login"); final NameValuePair url = new NameValuePair("url", "/?m=Login&func=do_login"); final NameValuePair userid = new NameValuePair("email", "david.jimenez19%40gmail.com"); final NameValuePair password = new NameValuePair("input_password", "linda1"); final NameValuePair timeZone = new NameValuePair("timezone", "1"); final NameValuePair timeStamp = new NameValuePair("timezone", "13034395121"); authpost.setRequestBody(new NameValuePair[] { action, url, userid, password, timeZone, timeStamp }); client.executeMethod(authpost); System.out.println("Login form post: " + authpost.getStatusLine().toString()); // release any connection resources used by the method authpost.releaseConnection(); // See if we got any cookies // The only way of telling whether logon succeeded is // by finding a session cookie final Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies()); System.out.println("Logon cookies:" + logoncookies); checkCookies(logoncookies); manageRequest(client, authpost); }
From source file:de.mpg.imeji.presentation.util.LoginHelper.java
/** * Get handle of System administrator of eSciDoc instance. * // ww w. j a va 2 s .c o m * @return */ // public static String loginSystemAdmin() // { // String handle = null; // try // { // handle = login(PropertyReader.getProperty("framework.admin.username"), // PropertyReader.getProperty("framework.admin.password")); // } // catch (Exception e) // { // sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class); // BeanHelper // .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e); // logger.error("Error escidoc admin login", e); // } // return handle; // } public static String login(String userName, String password) throws Exception { String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url"); StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//"); tokens.nextToken(); StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":"); String host = hostPort.nextToken(); int port = 80; if (hostPort.hasMoreTokens()) { port = Integer.parseInt(hostPort.nextToken()); } HttpClient client = new HttpClient(); client.getHttpConnectionManager().closeIdleConnections(1000); client.getHostConfiguration().setHost(host, port, "http"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userName); login.addParameter("j_password", password); try { client.executeMethod(login); } catch (Exception e) { throw new RuntimeException("Error login in " + frameworkUrl + " status: " + login.getStatusCode() + " - " + login.getStatusText()); } login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod("/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + postMethod.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:com.wafersystems.util.HttpUtil.java
/** * ?URLCookie?//from w ww . ja v a 2 s. co m * * */ public static void getCookie(String ip, int port, String path, boolean secure, Cookie[] httpCookies) { CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] cookies = cookiespec.match(ip, port, path, secure, httpCookies); if (cookies.length == 0) logger.debug("Cookie?"); else { logger.debug("Cookie?"); for (int i = 0; i < cookies.length; i++) logger.debug(cookies[i].toString()); } }
From source file:de.mpg.mpdl.inge.util.AdminHelper.java
/** * Logs in the given user with the given password. * /* w w w . j a v a 2s.co m*/ * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = PropertyReader.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String( Base64.getDecoder().decode(location.substring(index + 1, location.length()))); // System.out.println("location: "+location); // System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:de.mpg.escidoc.services.framework.AdminHelper.java
/** * Logs in the given user with the given password. * //w w w . ja v a 2 s.c o m * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password) throws HttpException, IOException, ServiceException, URISyntaxException { String frameworkUrl = ServiceLocator.getLoginUrl(); int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); ProxyHelper.executeMethod(client, login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); ProxyHelper.executeMethod(client, postMethod); if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); //System.out.println("location: "+location); //System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:de.mpg.escidoc.http.Login.java
private Cookie passSecurityCheck() { String loginName = Util.input("Enter Username: "); String loginPassword = Util.input("Enter Password: "); int delim1 = this.FRAMEWORK_URL.indexOf("//"); int delim2 = this.FRAMEWORK_URL.indexOf(":", delim1); String host;/* www .ja v a 2s. c om*/ int port; if (delim2 > 0) { host = this.FRAMEWORK_URL.substring(delim1 + 2, delim2); port = Integer.parseInt(this.FRAMEWORK_URL.substring(delim2 + 1)); } else { host = this.FRAMEWORK_URL.substring(delim1 + 2); port = 80; } PostMethod post = new PostMethod(this.FRAMEWORK_URL + "/aa/j_spring_security_check"); post.addParameter("j_username", loginName); post.addParameter("j_password", loginPassword); try { this.client.executeMethod(post); } catch (HttpException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } post.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(host, port, "/", false, this.client.getState().getCookies()); Cookie sessionCookie = logoncookies[0]; return sessionCookie; }
From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java
/** * Logs in the given user with the given password. * /*ww w . j a v a 2 s.c om*/ * @param userid The id of the user to log in. * @param password The password of the user to log in. * @return The handle for the logged in user. * @throws HttpException * @throws IOException * @throws ServiceException * @throws URISyntaxException */ public static String loginUser(String userid, String password, String frameworkUrl) throws HttpException, IOException, ServiceException, URISyntaxException { int delim1 = frameworkUrl.indexOf("//"); int delim2 = frameworkUrl.indexOf(":", delim1); String host; int port; if (delim2 > 0) { host = frameworkUrl.substring(delim1 + 2, delim2); port = Integer.parseInt(frameworkUrl.substring(delim2 + 1)); } else { host = frameworkUrl.substring(delim1 + 2); port = 80; } HttpClient client = new HttpClient(); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check"); login.addParameter("j_username", userid); login.addParameter("j_password", password); client.executeMethod(login); login.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); // Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies()); Cookie sessionCookie = client.getState().getCookies()[0]; PostMethod postMethod = new PostMethod(frameworkUrl + "/aa/login"); postMethod.addParameter("target", frameworkUrl); client.getState().addCookie(sessionCookie); client.executeMethod(postMethod); if (HttpStatus.SC_SEE_OTHER != postMethod.getStatusCode()) { throw new HttpException("Wrong status code: " + login.getStatusCode()); } String userHandle = null; Header headers[] = postMethod.getResponseHeaders(); for (int i = 0; i < headers.length; ++i) { if ("Location".equals(headers[i].getName())) { String location = headers[i].getValue(); int index = location.indexOf('='); userHandle = new String(Base64.decode(location.substring(index + 1, location.length()))); // System.out.println("location: "+location); // System.out.println("handle: "+userHandle); } } if (userHandle == null) { throw new ServiceException("User not logged in."); } return userHandle; }
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
/** * Initializes the underlaying http-protocol-provider from the given Propterties. * This sets the tcp-timeouts, the proxy-settings and ssl-settings. * @param prop containing properties for http and https protocol *//*from w w w . j a va 2 s .c o m*/ public static void init(Properties prop) { log_ = Logger.getLogger("boot.transport.http"); //$NON-NLS-1$ // proxy properties String strProxyEnable = prop.getProperty(Statics.CFG_PROP_PROXYENABLE); if (strProxyEnable != null && Boolean.valueOf(strProxyEnable).booleanValue()) { String strProxyServer = prop.getProperty(Statics.CFG_PROP_PROXYSERVER); String strProxyPort = prop.getProperty(Statics.CFG_PROP_PROXYPORT); if (strProxyServer != null && strProxyPort != null) { System.setProperty("proxySet", "true"); System.setProperty("http.proxyHost", strProxyServer); System.setProperty("http.proxyPort", strProxyPort); log_.log(LogLevel.FINE, "transport proxy is: {0}:{1}", new Object[] { strProxyServer, strProxyPort }); } String strSecureProxyServer = prop.getProperty(Statics.CFG_PROP_SECUREPROXYSERVER); String strSecureProxyPort = prop.getProperty(Statics.CFG_PROP_SECUREPROXYPORT); if (strSecureProxyPort != null && strSecureProxyServer != null) { System.setProperty("https.proxyHost", strSecureProxyServer); System.setProperty("https.proxyPort", strSecureProxyPort); log_.log(LogLevel.FINE, "secure transport proxy is: {0}:{1}", new Object[] { strSecureProxyServer, strSecureProxyPort }); } String strProxyOverride = prop.getProperty(Statics.CFG_PROP_PROXYOVERRIDE); if (strProxyOverride != null) { strProxyOverride = strProxyOverride.replace(';', '|'); // documented delimiter for IE strProxyOverride = strProxyOverride.replace(',', '|'); // IE supports ',' as delimiter, too strProxyOverride = strProxyOverride.replace(' ', '|'); // IE supports blank as delimiter, too strProxyOverride = strProxyOverride.replace('\t', '|'); // IE supports tab as delimiter, too strProxyOverride = strProxyOverride.replace('\r', '|'); // IE supports carriage return as delimiter, too strProxyOverride = strProxyOverride.replace('\n', '|'); // IE supports newline as delimiter, too strProxyOverride = strProxyOverride.replaceAll("<local>", "localhost|127.0.0.1"); System.setProperty("http.nonProxyHosts", strProxyOverride); log_.log(LogLevel.FINE, "proxy not used for: {0}", strProxyOverride); } } else { log_.log(LogLevel.FINE, "no transport proxy is used"); } // timeout properties String strConnectTimeout = prop.getProperty(Statics.CFG_PROP_CONNECTTIMEOUT); if (strConnectTimeout != null) { System.setProperty("sun.net.client.defaultConnectTimeout", strConnectTimeout); log_.log(LogLevel.FINE, "http connect timeout: " + strConnectTimeout + " milliseconds"); } String strReadTimeout = prop.getProperty(Statics.CFG_PROP_READTIMEOUT); if (strReadTimeout != null) { System.setProperty("sun.net.client.defaultReadTimeout", strReadTimeout); log_.log(LogLevel.FINE, "http read timeout: " + strReadTimeout + " milliseconds"); } // ssl properties String strTrustStore = prop.getProperty(Statics.CFG_PROP_SECURECERTS); if (strTrustStore != null) { log_.log(LogLevel.FINE, "using trusted certificates file " + strTrustStore); File trustFile = new File(strTrustStore); if (!trustFile.exists()) { log_.log(LogLevel.SEVERE, "trusted certificates file '" + trustFile.getAbsolutePath() + "' not found"); } System.setProperty("javax.net.ssl.trustStore", strTrustStore); } hostnameVerifier = new HostnameVerifierImpl(prop.getProperty(Statics.CFG_PROP_HOSTNAMEVERIFYIGNORE)); // cookie handling policy Class<?> cookiePolicyClass = null; String strCookiePolicy = prop.getProperty(Statics.CFG_PROP_COOKIEPOLICY); if (strCookiePolicy != null) { try { cookiePolicyClass = Class.forName(strCookiePolicy); } catch (ClassNotFoundException e) { log_.log(LogLevel.WARNING, "configured cookiePolicy '" + strCookiePolicy + "' not found, using default"); } } if (cookiePolicyClass == null) { cookiePolicyClass = CookieSpecBase.class; } log_.log(LogLevel.FINE, "using cookiePolicy " + cookiePolicyClass.getName()); CookiePolicy.registerCookieSpec(CookiePolicy.DEFAULT, cookiePolicyClass); cookieSpec = CookiePolicy.getDefaultSpec(); }