我在 Mac 上使用 vscode,并且有一个 Flutter 应用程序需要连接到 url api,例如:www.test.com
使用内部 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.
我可以通过模拟器网络浏览器和用于测试的物理设备访问 api url。所以 URL 处于活动状态并且连接未被阻止。
我确实拥有相关权限,例如:
android.permission.INTERNET
android.permission.ACCESS_NETWORK_STATE