45
votes

I m building a flutter app with django rest-framework. The registration api is working fine in Postman but after some successful registration from the flutter app it is showing the above error. The request is been sent on https address.

Removed csrf. Nothing happens.

Request:

var data = {'email':signupemailidcontroller.text,
            'password1':passwordcontroller.text,
            'password2':confirmpasswordcontroller.text,
           };
        //http request here
        await http.post(websitesignupurl,
                        headers: headers,
                        body: json.encode(data))
          .then((onResponse){
            print(onResponse.body);
          }).catchError((onerror){
            print(onerror.toString());
        });

Output in Console:

SocketException: OS Error: Connection refused, errno = 111

I Expect the response of this request to be a Json object containing the user and token.

15
Harnish if the answer I have given below helped you, do consider marking it as the accepted answer. So that we can help others who have the same question. - Rohan Thacker
is this being run on PythonAnywhere? if you have a free user account, then you will only be able to make http posts to endpoints on the PythonAnywhere whitelist pythonanywhere.com/whitelist - conrad

15 Answers

97
votes

Harnish, need a few more details in-order to debug this error.

  1. Are you running the server locally or communicating with a remote server?
  2. Are you running the app on the Android Emulator?

Possible Solution:

If you're running the server locally and using the Android emulator, then your server endpoint should be 10.0.2.2:8000 instead of localhost:8000 as AVD uses 10.0.2.2 as an alias to your host loopback interface (i.e) localhost

Note on Futures

I noticed above that the code is using await and then on the same line. This can be confusing, to be clear, await is used to suspend execution until a future completes, and then is a callback function to execute after a future completed. The same could be written as below

void myFunction() async {
    var data = {};
    var response = await http.post(URL, headers:headers, body:data);
    if (response.statusCode == 200) {
        print(reponse.body);
    } else {
       print('A network error occurred');
    }
}

or the non async/await method

void myFunction() {
    var data = {};
    http.post(URL, headers:headers, body:data)
    .then((response) => print(response.body))
    .catchError((error) => print(error));
}

For a more detailed information on Futures in Dart please read https://www.dartlang.org/tutorials/language/futures

14
votes

I went to the terminal and used ifconfig command

I got my IP address: 192.168.0.109

enter image description here

Then I simply replaced this IP address with my "localhost" in flutter app http requests. And it worked like a charm!

9
votes

In addition to Rohan's answer you can also read:

Unable to make calls to Localhost using Flutter, random port being assigned to HTTP GET call

I was trying to run my app on physical device using local server so, for that i had to use the below mentioned command, here keep in mind change the port number according to your own port number

adb reverse tcp:3001 tcp:3001

As @maheshmnj pointed that this command is redirecting your phone's port 3001 to your computer's port 3001. In case if you want to redirect port 2000 of your phone to port 3000 of your computer then you could do this adb reverse tcp:2000 tcp:3000

you can also read about adb and networking via going through below mentioned page https://developer.android.com/studio/command-line/adb.html

6
votes
  • if in localhost instead localhost use the IP of your network
  • hint:for find Ip in cmd run ipconfig and get the ipv4

1: Example:

await http.post("http://127.68.34.23/wp-json/...",
                    headers: headers,
                    body: json.encode(data))

if in server write the url of main in url

4
votes

Try adding <uses-permission android:name="android.permission.INTERNET"/> to your manifest. This solved this issue for me.

3
votes

If you are using 'localhost' in your url, change it to your ipv4 address and it will work

2
votes

This is what I had to change to fix the same error in my case:

  • Start django with python manage.py runserver 0:8000 and not just python manage.py runserver (0:8000 is the abbreviation for 0.0.0.0:8000 and makes your web application visible on your local network - see https://docs.djangoproject.com/en/3.0/ref/django-admin/#runserver)
  • In your flutter app specify the server address using your pc local ip, i.e. instead of http://localhost:8000 use something like http://192.168.1.2:8000. To retrieve your current ip address run ipconfig in the terminal if on Windows, otherwise ifconfig.
  • Update allowed host in django settings if necessary. For example set ALLOWED_HOSTS = ['*', ] (but only in your dev environment!)
2
votes

I had the same problem running in a real device, and only changing the IP in API link doesn´t work.

The solution for me was to put the server run with the command below:

manage.py runserver 0.0.0.0:8000

Then pass your machine IP to the API link instead of localhost, as the sample below:

http://192.168.0.67:8000
2
votes

In C#[.net core api], go to launchSettings.json under Properties tab and change the follwing code to this(change localhost to 0.0.0.0 on applicationURl) and on the app(flutter), use ur local IPV4 IP. ex: (192.169.0.10)

"coreWebAPI": {
      "commandName": "Project",
      "launchBrowser": false,
      "launchUrl": "api/values",
      "applicationUrl": "http://0.0.0.0:5000", 
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
1
votes

I fixed this with $ adb tcpip <port-your-local-server>

1
votes

I had the same issue in flutter with spring backend. Instead of using 'http://localhost:8080/' in my requests, I changed this to 'http://143.235.7.641:8080/' where '143.235.7.641' is my Wi-Fi IPv4 address, and it worked.

(NOTE : I assume you are testing flutter in physical phone,and phone and computer are connected the same wi-fi.)

0
votes

What you need to do is to get your public PC IP and use it in your URL for example: http://192.168.0.67:3000, where 3000 is the port no.

0
votes

I had this same issue once, After going through some overly complicated stackoverflow answers and google search, finally i figure it out, In this case you are most likely to be using a android emulator, So just turn on the mobile data on the emulator then try it again, i'm sure that this time it will work.

0
votes
final response = await client.post(
    "http://192.xxx.xx.xx/api/signin", 
    headers: {"Authorization": apiKey},
    body: jsonEncode({
      "username": username,
      "password": password,
    }));

Even I had got a SocketException Error but I replaced my IP address and didn't mention any Port number and it worked for me, and if I mention the port number it would throw an error. Hoping this would work out.

I am using Flask for backend ,using blocs.

0
votes

This problem occurs when the endpoint are incorrect or you host and server backend (Example Laravel API)doesn't share the same IP address.

Solution is.

  1. Connect your workspace (computer, emulator, devices) in same network.
  2. Find your IP by typing on terminal ifconfig.
  3. If you build your API with Laravel, start the server appointing to IP ADDRESS of your computer, sudo php artisan serve --host YOUR_COMPUTER_IP_ADDRESS --port NUMBER

Example:

`sudo php artisan serve --host 192.168.1.11 --port 80`
  1. Test your endpoint in Postman or similar Application and type http://192.168.1.11:80/Your_Route
  2. If everything is working good, you can run with app. Go!!!