Code to login not working
could anyone help me with figuring out why this code isn't working? It's supposed to log into HTS, but it doesn't work. It's not giving me any error messages or anything, just no result at all. Any help would be appreciated.
Here's the code:
import java.net.*;
import java.io.*;
public class Login {
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
URLObj = new URL("http://www.hackthissite.org/user/login");
connect = URLObj.openConnection();
connect.addRequestProperty("REFERER", "http://www.hackthissite.org");
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
BufferedWriter writer = new开发者_C百科 BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));
writer.write("username=BrandonHeat&password=**********&btn_submit=Login");
writer.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
}
i'm just guessing, but the documentation for URLConnection indicates that you must connect after having set the parameters :
1.The connection object is created by invoking the openConnection method on a URL.
2.The setup parameters and general request properties are manipulated.
3.The actual connection to the remote object is made, using the connect method.
4.The remote object becomes available. The header fields and the contents of the remote object can be accessed.
...
The following methods are used to access the header fields and the contents after the connection is made to the remote object:
- getContent
- getHeaderField
- getInputStream
- getOutputStream
Edit :
can't you open the URL with you parameters in the URL (ie http://www.hackthissite.org/user/login?username=BrandonHeat&password=xxxxx&btn_submit=Login), or setted as header ?
also, after the connect(), what do you get if you do a getContent() ?
Edit : there is a description of the process here.
Regards
Guillaume
精彩评论