I want to send data from Java to a PHP page. I have googled a bit but the code I am finding is not working here is an example of the code I have used:
URL url = new URL("http://test.PHP");
URLConnection con = url.openConnection();
PrintStream ps = new PrintStream(con.getOutputStream());
What I need to do is input a username and password on the page and have the PHP page accept the input and actually run the log in function (Simulate as if a user pressed the button).
Best How To :
When we try to use code to simulate action done in the browser , one of the best API in the Java world is HTTPClient, which give you many features that make your code act as a user in front of a browser (fill input, click, load link ...) . here is a good tutorial to start.
But in case that you want to use just the stardard Java API without any third party library, there here is a few lines that i hope it would be helpful :
first try to specify in the url the domaine name and the page that you want to invoke when requesting the server ex:
URL url = new URL("http://www.mydomaine.com/test.PHP");
if the website show a popup for authentication login/pass when trying to access then try this url instead :
URL url = new URL("http://login:[email protected]/test.PHP");
if it show you a login form and you try to access is by sending your login and pass as if you fill the input then, the first thing is to identify the name of the input that will be used when we send request to the server , it may be
password or something else, to find those name try to inspect the page from the browser (view the source code of the page or try inspecting HTML elements) you will find something like this :
<form action="login.php" method="POST">
<input type="text" name="my_login">
<input type="password" name="my_password">
let's suppose that the names are
my_password , in this case the the page that you have to invoke is login.php (which is the value of the action form) your code will be :
URL obj = new URL("http://www.mudomaine.com/login.php);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String datas = "my_login=Administrator&my_password=s3cred0n3";
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
You can handle the result by calling
con.getInputStream() if you want to manage the server result .
But i will repeat again , if you can use a third library then use it , because it simplify the job , and reduce possible bug in your code.