Sat Apr 21, 2012 4:25 am by smmortazavi
I have done this in one groovy before and I share it here hoping it helps.
use login() method bellow first and after a successful login include login cookie ("PHPSESSID=$loginCookie") in all subsequent requests:
- Code:
def String login() {
def url = "http://www.ilive.to/login"
def userName="myuser"
def paswd="mypass"
String loginCookie = getCookie(url,"PHPSESSID");
String loginResult = doPOST(url, "username=$userName&password=$paswd", "PHPSESSID=$loginCookie")
return loginResult
//If login is successfull make all other subsequent requests with the above cookie ("PHPSESSID=$loginCookie") to get the extended channel list
}
def String getCookie(String _url, String cookieName) throws Exception{
def headerName, rv = "Not Found";
// creeating the url connection object
URL url = new URL(_url)
URLConnection urlConnection = url.openConnection();
// checking for each headers
for (int i=1; (headerName = urlConnection.getHeaderFieldKey(i))!=null; i++) {
// if its set-cookie, then take it
if (headerName.equalsIgnoreCase("Set-Cookie")) {
String cookie = urlConnection.getHeaderField(i);
String cName = cookie.split("=")[0];
String cValue = cookie.split("=")[1];
if (cName.equalsIgnoreCase(cookieName))
return cValue.replaceAll(";.*","")
}
}
return rv;
}
def String doPOST(String _url, String data, String cookie) {
// Construct data
def rv = ""
URL url = new URL(_url);
URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", cookie);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
rv += line
}
wr.close();
rd.close();
return rv
}