In my flutter app I am using the flask server for testing purpose. I started my server and run the API url in my flutter app. But SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 44164. error is showing.
var headers = {'Content-Type': 'application/json'};
var request =
http.Request('POST', Uri.parse('http://127.0.0.1:5000/addrec'));
request.body = json.encode({
"name": UploadedName,
"grade": Uploadedgrade,
"loaction": Uploadedlocation,
"like": Uploadedlike,
"admission": Uploadedadmission,
"comments": Uploadedcomments,
"entery_time": UploadeddataentryTime
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
I am using actual android device for app running.
CodePudding user response:
This happens because the localhost
(or 127.0.0.1
) on the device is only accessible to the device itself.
Solution 1
You can reverse-proxy a localhost
port to the Android device/emulator running adb reverse
on the command prompt like so:
adb reverse tcp:5000 tcp:5000
Solution 2
Use the machine's IP address where the API is running. Also, the API should be listening to the IP 0.0.0.0
to be accessible outside the localhost.
Supposing the API machine's IP is 192.168.1.123
it's going to be something like:
Uri.parse('http://192.168.1.123:5000/addrec')
Just take care because changing the API to listen to 0.0.0.0
is a security risk as the API is going to be accessible to the outside world.