I am trying to submit data from Android to my php server. However all the answers seem to use the deprecated apache http library. I do not want to use that, and when I tried it didn't work.
Right now it it does not seem to do anything. It seems to connect to the web server, but the server does not write any data. If I just visit the url with the browser, it will write to a file.
The php code is
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"];
// specify the file where we will save the contents of the variable message
$filename="androidmessages.html";
// write (append) the data to the file
file_put_contents($filename,$message."<br />",FILE_APPEND);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>
Then in Android studio, I am putting all of the code after a button press
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadingProgressBar.setVisibility(View.VISIBLE);
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
System.out.println("This is a test");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//Your code goes here
URL url = null;
OutputStream out = null;
String urlString = "https://mywebsite.net/php_script.php";
String data = "HelloWorld"; //data to post
try {
url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoOutput(true);
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}