Search code examples
androidhttplocalhostform-data

Sending and Retrieving data from Android App to API URL (localhost)


I have tried every other solution from number of websites to send form-data to PHP Laravel server and retrieve data from that server like retrofit2 (it was giving some firebase errror, I tried to fix but couldn't do so I simple gave up on that) then this Android Asynchronous Http Client ('com.loopj.android:android-async-http:1.4.9') came in front of me so I decided to test, now the problem is that my server is running at address: http://localhost:8000/api/complaints?username=abduul and when I try to get response from this url from my android app it gives this error:

java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 8000) from /127.0.0.1 (port 59252) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)

I think it might be the problem with port number as I am testing on android emulator.

The code I am tryna use is:

public void getData() {
    final AsyncHttpClient client = new AsyncHttpClient();

    client.get("http://localhost:8000/api/complaints?username=abduul", null, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            System.out.println(response);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {

        }
    });
}

and one thing I even tried using XAMPP server but then it says

java.net.UnknownHostException: Unable to resolve host "laravel.btsp": No address associated with hostname

this "laravel.btsp" is defined in host file and note that both of the URLs are working perfectly fine on browser

EDIT: even these two URLs are working fine with POSTMAN, I tried sending and getting data from POSTMAN, it works but gives error with this code and on Android


Solution

  • If you are using Android Emulator, use 10.0.2.2 instead of localhost (127.0.0.1). Because the localhost refers to emulator device and not the machine you are using to run the emulator.