skip to Main Content

I want to display data sent from an android app using POST request to a simple html website whenever a button in the app is pressed. I’m hosting the website and the php file to handle the POST in xampp apache, I’ve set up the server so the app on my smartphone can access it via local ip and port (192.168.x.xx:8080), but I keep getting the 404 error not found. Can you guys help me?

The PHP file to handle the POST request:

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === 'siteteste/message_handler.php') {
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);
    
    if(isset($request->message)) {
        $message = $request->message;
    } else {
        http_response_code(400);
        echo "Error: Message field is missing";
    }
} else {
    http_response_code(404);
    echo "Not Found";
}
?>

The HTML code:

<body>
    <div id="messageContainer"></div>
    
    <script>
        function fetchMessage() {
            fetch('message_handler.php')
            .then(response => response.text())
            .then(messageHtml => {
                document.getElementById('messageContainer').innerHTML = messageHtml;
            })
            .catch(error => console.error('Error fetching message:', error));
        }

        fetchMessage();

        setInterval(fetchMessage, 5000);
    </script>
</body>

The java class to send the POST request:

import android.os.AsyncTask;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SendMessage {
    public void sendMessage() {
        new SendMessageTask().execute();
    }

    private class SendMessageTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL url = new URL("http://192.168.xx.xx:8080/siteteste/message_handler.php");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setDoOutput(true);
                con.setRequestProperty("Content-Type", "application/json");

                String message = "Atenção: O operador X do ponto Y do setor Z precisa de suporte!";

                try (OutputStream os = con.getOutputStream()) {
                    byte[] input = message.getBytes("utf-8");
                    os.write(input, 0, input.length);
                }

                int responseCode = con.getResponseCode();
                System.out.println("Response code: " + responseCode);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

Whenever I press the button which sends the request, I get a 404 error as the responseCode, but when I check the logs on xampp files, I can see that the device I’m running the app has access to the server

192.168.xx.xx - - [05/Mar/2024:00:05:36 -0300] "POST /siteteste/message_handler.php HTTP/1.1" 404 9 "-" "Dalvik/2.1.0 (Linux; U; Android 12; SM-G780G Build/SP1A.210812.016)"

Also I get this error everytime the fetchMessage() function update when I open the website on the browser (Chrome DevTools)
siteteste.html:13 GET http://192.168.xx.xx:8080/siteteste/message_handler.php 404 (Not Found)

What am I doing wrong?
Thanks a lot for the help and sorry for any mistakes, english is not my first language.

2

Answers


  1. The issues you’re facing, both with the Android app receiving a 404 error when sending a POST request and the browser error when trying to fetch messages, likely stem from how the server and script paths are configured in your XAMPP Apache setup and how you’re referencing the PHP script in your requests.
    Android POST Request Issue

    Check the PHP File Location: Ensure that message_handler.php is located at the correct path relative to your web server’s root directory. Based on the URL you’re trying to access (http://192.168.15.72:8080/siteteste/message_handler.php), your message_handler.php should be inside a directory named siteteste within the htdocs directory of your XAMPP installation.

    Correct PHP Script Path Handling: The condition $_SERVER[‘REQUEST_URI’] === ‘siteteste/message_handler.php’ might not work as expected because REQUEST_URI includes the leading slash /, and possibly more path information depending on your server configuration. Try modifying the condition to correctly reflect the path, or simply remove this check to test if the script is being reached:

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && strpos($_SERVER['REQUEST_URI'], 'siteteste/message_handler.php') !== false) {
    

    Browser Fetch Issue

    Incorrect Fetch Method: Your JavaScript fetch call does not specify that it’s a POST request and does not send any data. However, your PHP script is expecting a POST request with JSON data. If you’re trying to fetch the message with GET, you’ll need a separate handling mechanism or endpoint for that, or you need to adjust your fetch to match what the PHP expects for a POST:

    function fetchMessage() {
    fetch('message_handler.php', {
        method: 'POST', // Specify the method
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ message: 'Your message here' }) // Send some data
    })
    .then(response => response.text())
    .then(messageHtml => {
        document.getElementById('messageContainer').innerHTML = messageHtml;
    })
    .catch(error => console.error('Error fetching message:', error));}
    

    Same Path Issue: The JavaScript fetch path ‘message_handler.php’ assumes that the HTML file is in the same directory as message_handler.php. If your HTML file is not in the siteteste directory alongside message_handler.php, you’ll need to adjust the fetch path to match the correct relative or absolute path.

    General Debugging Tips

    Check File Permissions: Ensure that message_handler.php has the correct file permissions to be readable and executable by the web server.
    Apache Configuration: Check .htaccess files and Apache configuration for any rewrite rules or configurations that might affect how URLs are resolved.
    Logs: Review Apache’s error logs for more detailed messages about why the file might not be found. These logs can provide valuable insight into path resolution issues or file access problems.

    Ensure your server’s directory structure matches your URL paths, and adjust your request handling and paths accordingly.

    Login or Signup to reply.
  2. Your IP address is wrong. Unless you’re running the server on your phone (and you aren’t, as Android doesn’t run servers well), then the IP isn’t localhost. If you’re using an emulator, use 10.0.2.2. That’s a private network set up between the emulator and the PC it’s running on to allow it to contact that PC. If you’re on a real device, use the IP address of the device and make sure that your firewall is configured to allow incoming traffic to the port you set it up on. And if you don’t know if you have a firewall, you almost certainly do built into your wifi router. Also, if a real device make sure you’re using wifi not the internet, as there’s no way to make that route properly without a public IP address.

    Also, make sure that you set android:usesCleartextTraffic=”true” in your AndroidManifest application tag, unless you’re using HTTPS for the server. Also remember that the Play Store will not likely accept your app with that flag if you try to release it there, use it for debug only.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search