twilio API 修复的主机查找失败?

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

我正在尝试将 Twilio API 与 Whatsapp 发送器结合使用,以便在我的 flutter 应用程序中发送通知。当尝试调用 API 时,应用程序崩溃并引发一些异常。没有发生,因为帐户 sid 和身份验证令牌中没有任何内容(已删除它们,以便我可以向代码显示)。

**调用堆栈**:_NativeSocket.lookup。 (dart:io-patch/socket_patch.dart:520) (来源不明:0) _NativeSocket.staggeredLookup..lookupAddresses。 (dart:io-patch/socket_patch.dart:0) (来源不明:0)

异常:“没有与主机名关联的地址”,“主机查找失败:'api.twilio.com'”

Future<void> sendWhatsAppMessage(
    String recipientWhatsAppNumber, String message) async {
  const twilioAccountSid = '';
  const twilioAuthToken = '';
  const twilioNumber = '+15066160178';

  final basicAuth =
      'Basic ${base64Encode(utf8.encode('$twilioAccountSid:$twilioAuthToken'))}';

  final Uri uri = Uri.parse(
      'https://api.twilio.com/2010-04-01/Accounts/$twilioAccountSid/Messages.json');

  final Map<String, String> body = {
    'To': 'whatsapp:$recipientWhatsAppNumber',
    'From': twilioNumber,
    'Body': message,
  };

  final response = await http.post(
    uri,
    headers: <String, String>{
      'authorization': basicAuth,
      'content-type': 'application/x-www-form-urlencoded',
    },
    body: body,
  );

  if (response.statusCode == 200) {
    print('WhatsApp message sent successfully.');
  } else {
    print(
        'Failed to send WhatsApp message. Status code: ${response.statusCode}');
  }
}```




I tried wrapping the code bits in try and catch blocks and it doesn't even catch the error and crashes the application.
flutter dart twilio twilio-api
1个回答
0
投票

您需要在清单中启用互联网访问权限。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.app">
<uses-permission android:name="android.permission.INTERNET" />
© www.soinside.com 2019 - 2024. All rights reserved.