При тестировании с использованием внутреннего IP-адреса, например: 10.0 .0.3:80/api/Values/ приложение нормально подключается, публикует и получает данные.
при внешнем тестировании с использованием URL-адреса приложение завершается со следующей ошибкой: сеть недоступен, адрес не связан с именем хоста.
Код:
Future fetchAndSaveNotificationData() async {
String? registrationHexNumber ="0";
try {
// Replace with your username and password
String username = 'UserName';
String password = 'PassWord';
// Encode username and password using Base64 for Basic Authentication
String basicAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password'));
final url = Uri.parse('http://www.test.com/api/Values/');
print(' over here 01 ${url.toString()}');
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Authorization': basicAuth,
},
body: jsonEncode({
'registrationHexNumber': registrationHexNumber,
}),
);
print('over here 02 ${url.toString()}');
if (response.statusCode == 200) {
// Decode the JSON response
}
} else {
}
} catch (e) {
print("Error: $e");
}
}
похоже, проблема здесь:
print(' over here 01 ${url.toString()}'); // i get up to here
final response = await http.post(
url,
headers: {
'Content-Type': 'application/json',
'Authorization': basicAuth,
},
body: jsonEncode({
'registrationHexNumber': registrationHexNumber,
}),
);
print('over here 02 ${url.toString()}'); // i do not get here.
Я могу получить доступ к URL-адресу API через веб-браузер эмулятора и физическое устройство, используемое для тестирования. Таким образом, URL-адрес активен и соединение не заблокировано.
У меня есть соответствующие разрешения, такие как:
- android.permission.INTERNET
- android.permission.ACCESS_NETWORK_STATE
Похоже, это проблема только Android. Протестировано iOS, работает как положено.
Эмулятор имеет необходимый доступ к Интернету.
Изменить: В файл добавлено следующее: выполните проверку соединения из приложения:
Future testConnection() async {
try {
print('Testing connection...');
// Try to resolve the domain
print('Looking up domain...');
final addresses = await InternetAddress.lookup('test.com');
print('Domain resolved to: ${addresses.map((a) => a.address).join(', ')}');
// Try to ping the first address
if (addresses.isNotEmpty) {
final socket = await Socket.connect(addresses.first.address, 80,
timeout: Duration(seconds: 5));
print('Successfully connected to socket');
await socket.close();
}
} catch (e) {
print('Connection test error: $e');
}
}
Выход:
I/flutter ( 8850): Testing connection...
I/flutter ( 8850): Looking up domain...
I/flutter ( 8850): Domain resolved to: xxx.xxx.xxx.xxx
I/flutter ( 8850): Successfully connected to socket
Подробнее здесь: https://stackoverflow.com/questions/791 ... ects-to-lo
Мобильная версия