I'm using Android Studio / Java for my mobile app project, I have a login activity in which I let the user to put their email and password to log into the app, and once they click the 'submit' button, I fire a POST
request to post the details to the server (PHP page).
The request hits the PHP page on the server, but the details (email, password) are located in the $_GET
array instead of the $_POST
array. That means it is a GET
request and not a POST
request.
So this is the code I saw 100s of upvoted and accepted answers that suggested to use for POST
requests. This code generates a GET
request and NOT a POST
request, (The parameters received in PHP will be in the $_GET
array instead of the $_POST
array):
String postData = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" + URLEncoder.encode("password", "UTF-8");
URL url = new URL("http://localhost/home.php?" + postData);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine, result = "";
while ((inputLine = reader.readLine()) != null) {
result += inputLine;
}
reader.close();
return result;
}
Note: I expect to get a string as a response back from PHP for this post request.
Maybe the fact that I attach the post data to the url as parameters is what makes it a GET
request? There is another way to attach the data to the request body?
My question is: How do I make a pure POST
request that will actually post the data to PHP using HttpURLConnection
? And I will be very clear here: By POST
request I mean that the variables should not be sent through the url (this is GET
request), and I will be able to find the posted variables at the famously known $_POST
array.
How should the POST
request be made and how to fetch the server's response out of it?