Skip to content
Advertisement

java.net.ConnectException: Failed to connect to /localhost:8080

So, I’m trying to send a POST request from my android phone to my server (laptop) both on the same network. I am getting the error as shown above. I thought this could be something about the firewall thing, but I disabled it. I open the firefox console and see this error The script from “http://192.168.56.1:8080/upload_db.php” was loaded even though its MIME type (“application/x-httpd-php”) is not a valid JavaScript MIME type..

For some more background information, I am uploading (well trying) a .db file from my phone to the server. So here’s my code that I am using to upload this file.

    public class UploadTaskAsync extends AsyncTask<String, String, String>{

        @Override
        protected String doInBackground(String... strings) {
            try {

                String url = "http://192.168.56.1:8080/upload_db.php";
                String charset = "UTF-8";
                File dbFile= new File(Environment.getExternalStorageDirectory()+"/databasesFolder/userDB.db");
                String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
                String CRLF = "rn"; // Line separator required by multipart/form-data.

                URLConnection connection;

                connection = new URL(url).openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-sqlite3; boundary=" + boundary);

                try (
                        OutputStream output = connection.getOutputStream();
                        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
                ) {

                    writer.append("--" + boundary).append(CRLF);
                    writer.append("Content-Disposition: form-data; name="uploaded_file"; filename="" + dbFile.getName() + """).append(CRLF);
                    writer.append("Content-Type: application/x-sqlite3; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
                    writer.append(CRLF).flush();
                    FileInputStream vf = new FileInputStream(dbFile);
                    try {
                        byte[] buffer = new byte[1024];
                        int bytesRead = 0;
                        while ((bytesRead = vf.read(buffer, 0, buffer.length)) >= 0)
                        {
                            output.write(buffer, 0, bytesRead);

                        }
                        //   output.close();
                        //Toast.makeText(getApplicationContext(),"Read Done", Toast.LENGTH_LONG).show();
                    }catch (Exception exception)
                    {


                        //Toast.makeText(getApplicationContext(),"output exception in catch....."+ exception + "", Toast.LENGTH_LONG).show();
                        Log.d("Error", String.valueOf(exception));
                        publishProgress(String.valueOf(exception));
                        // output.close();

                    }

                    output.flush(); // Important before continuing with writer!
                    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.


                    // End of multipart/form-data.
                    writer.append("--" + boundary + "--").append(CRLF).flush();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // Request is lazily fired whenever you need to obtain information about response.
                int responseCode = ((HttpURLConnection) connection).getResponseCode();
                System.out.println(responseCode); // Should be 200

            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }


        @Override
        protected void onProgressUpdate(String... text) {
            Toast.makeText(getApplicationContext(), "In Background Task " + text[0], Toast.LENGTH_LONG).show();
        }

    }

This is the backend code that I’m using is as follows:

<?php 
$file_path = "C:\Users\<username>\Documents\";

$file = $file_path . basename($_FILES['uploaded_file']['name']);

if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file)) {
    echo "Uploaded";
} else {
    echo "fail";
}
?>

For the server setup, I am using the npm http-server. Is this because my server is not listening on port 8080 or is it on the android app end? It’d be great if anyone can point me in the right direction. This seemingly simple task is taking up way too much time. As far as I understand, the server does not require any authentication to accept post requests as I start the server using http-server .. The server opens just fine on the phone browser and I can see the index.html that was written. So, I know that server is operational. However, I have no idea where I am going wrong in the mobile app part.

Advertisement

Answer

The JS (NPM) HTTP Server doesn’t execute PHP scripts. You’d have to setup the infamous WAMP stack so that the PHP script is executed when you call it via URL.

Setting Up Apache/MySQL/PHP (AMP) on Linux (LAMP), Windows (WAMP) and Mac OS (MAMP)

On a side note, you can also use ADB Reverse to forward a port from your device to your laptop.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement