Hello everyone,
I'm a GSoC participant working for Eclipse Org. this year. As a part of my project , I need to authenticate, upload/download assignments through Eclipse workspace itself. But I'm kinda stuck with authenticating with the moodle server. Basically I need to send HTTP POST Requests through Java (programatically). I do something like this ..
URL url=new URL(loginPage.getServerURL().toString()+"/login/index.php");
URLConnection con=url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(true);
//con.setRequestProperty("Content-Type", "text/html");
DataOutputStream out=new DataOutputStream(con.getOutputStream());
String test=new String("username="+URLEncoder.encode("admin","UTF-8")+
"&password="+URLEncoder.encode("admin","UTF-8"));
out.writeBytes(test);
out.flush();
out.close();
Similarly , I get the output, after sending the request by:
DataInputStream in=new DataInputStream(con.getInputStream());
String buf;
while(null!=((buf=in.readLine())))
{
System.out.println(buf);
}
System.out.println(con.getURL());
in.close();
Well, unfortunately the above code takes me back to the moodle's homepage with a unsuccessful login. If I change the values of the username or password, I get the "Invalid username or password" error as expected in the output page. But with correct values it still doesn log in. I wonder if it has to do anythin with the cookie requirements ? Help needed ...
Thanks ,
Souvik
Try adding
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
after
con.setUseCaches(true);
See www.javaworld.com/javatips/jw-javatip34.html for an example.
Alternatively you could look at www.informit.com/guides/content.aspx?g=java&seqNum=44 which explains how to achieve what you want using the Jakarta Commons HttpClient class.
Hope this helps!
Stephan
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
after
con.setUseCaches(true);
See www.javaworld.com/javatips/jw-javatip34.html for an example.
Alternatively you could look at www.informit.com/guides/content.aspx?g=java&seqNum=44 which explains how to achieve what you want using the Jakarta Commons HttpClient class.
Hope this helps!
Stephan
Thanks Stephan But I've already tried out the first link, but still no luck. And I'm not very sure if I can use external API's for Eclipse (Not sure about the licensing part). But thanks a lot for the link, will as well use it for other projects