1

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();

        }
    });
}
Jiggly Wiggly
  • 21
  • 1
  • 1
  • 4
  • Have to tried to get request data via $data = file_get_contents('php://input');? Also check if app has internet permission and network security configuration https://developer.android.com/training/articles/security-config. – David Vareka Jun 25 '21 at 13:45

2 Answers2

2

Your PHP code is looking for a variable in $_POST called "message"

$message=$_POST["message"]; 

However in your Android code your just writing your message data to the http request body.

I suggest looking into Volley which is an HTTP library, and allows for easily making HTTP requests. This answer might also be of help.

DevWithZachary
  • 3,545
  • 11
  • 49
  • 101
  • Thanks for that. I am looking into Volley as well now. However when I throw a code snipping it inside the button loginButton.setOnClickListener(new View.OnClickListener() { for try { RequestQueue requestQueue = Volley.newRequestQueue(this); It complains about (this) Required type: Context Provided: OnClickListener – Jiggly Wiggly Jun 26 '21 at 00:47
1

You can use JSON and Volley for this!

<?php
$data = json_decode(file_get_contents('php://input'), true);
$filename="androidmessages.html";
file_put_contents($filename,$data["message"]."<br />",FILE_APPEND);
$reponse = array("message" => $androidmessages=file_get_contents($filename));
echo json_encode($reponse);
?>

and this in android (Kotlin):

private fun sendHtmlRequest(view: View){
    val jsonobj = JSONObject()
    var url = "https://URL.php"

    jsonobj.put("message", "test message")

    val que = Volley.newRequestQueue(context)
    val req = JsonObjectRequest(Request.Method.POST, url, jsonobj,
        Response.Listener { response: JSONObject ->
            val messageResponse = response.getString("message")
            println("response: $messageResponse")
        }, Response.ErrorListener{
            println("Error")
        }
    )

    que.add(req)
}
Slamit
  • 465
  • 1
  • 6
  • 21
  • val que = Volley.newRequestQueue(context), it says unresolved variable context, do I have to make that myself? Thanks – Jiggly Wiggly Jun 26 '21 at 01:05
  • If you are not un an activity you will need to provide the context too. Else you should be able to get the context with getContext() or "this" in Java – Slamit Jun 26 '21 at 10:07