Flutter Android 应用程序将无法连接到外部 url api。仅连接到本地内部 ip api

问题描述 投票:0回答:1

我在 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 处于活动状态并且连接未被阻止。

我确实拥有相关权限,例如:

  1. android.permission.INTERNET

  2. android.permission.ACCESS_NETWORK_STATE

flutter dart visual-studio-code
1个回答
0
投票

仅授予互联网许可是不够的。

您还必须确保您已在模拟器上连接到互联网,并确保“飞行模式”未打开。

飞行模式关闭

互联网连接状态

© www.soinside.com 2019 - 2024. All rights reserved.