Skip to content

Instantly share code, notes, and snippets.

@yousefamar
Created September 21, 2014 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yousefamar/5a2dfbcea877ea5032da to your computer and use it in GitHub Desktop.
Save yousefamar/5a2dfbcea877ea5032da to your computer and use it in GitHub Desktop.
An example of command-line login into a web server using Java
import java.io.*;
import java.net.*;
public class WebLogin {
public static String login(String username, String password) {
//TODO: Add version parameter.
String parameters = "username="+username+"&password="+password;
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL("http://www.4ytech.com/usr/javaLogin.php").openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(parameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(parameters);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = in.readLine();
in.close();
return response;
} catch (Exception e) {
return "Error: Unable to connect to 4ytech.com.";
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
Console c = System.console();
while (true) {
String username = c.readLine("Username: ");
String password = c.readLine("Password: ");
System.out.println(login(username, password));
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment