You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将React Native生成Basic认证头的代码改写为Dart代码

Convert React Native Basic Auth Header Logic to Dart

Sure thing! Let's translate that React Native Basic auth header logic into Dart. Here's the equivalent implementation that matches the original behavior perfectly:

import 'dart:convert';

// Make sure CONSUMER_KEY and CONSUMER_SECRET are defined in your code (e.g., as constants)
String generateAuthHeader() {
  // Encode key and secret (matches JavaScript's encodeURI)
  final encodedKey = Uri.encodeComponent(CONSUMER_KEY);
  final encodedSecret = Uri.encodeComponent(CONSUMER_SECRET);
  
  // Combine into the credentials string
  final credentials = '$encodedKey:$encodedSecret';
  
  // Encode to base64 (matches JavaScript's btoa)
  final base64Credentials = base64.encode(utf8.encode(credentials));
  
  // Return the full Basic auth header
  return 'Basic $base64Credentials';
}

Breakdown of the translation:

  • Uri.encodeComponent: This does exactly what encodeURI does in JavaScript—it encodes special characters (like spaces, slashes, or symbols) in your consumer key/secret to ensure they're safe for HTTP headers.
  • base64.encode combined with utf8.encode: JavaScript's btoa works with ASCII strings, so in Dart we first convert the credentials string to UTF-8 bytes (using utf8.encode) before base64 encoding it. This aligns perfectly with the original code's behavior since encodeURI outputs UTF-8 encoded characters.
  • Header construction: The final step of prepending "Basic " to the base64 string is identical to your React Native code.

Example usage with HTTP requests:

If you're using the popular http package to make API calls, here's how you'd use this header in practice:

import 'package:http/http.dart' as http;

Future<void> fetchProtectedData() async {
  final authHeader = generateAuthHeader();
  final response = await http.get(
    Uri.parse('https://your-api-domain.com/protected-endpoint'),
    headers: {'Authorization': authHeader},
  );
  
  // Handle the response as needed
  if (response.statusCode == 200) {
    print('Success!');
    print(response.body);
  } else {
    print('Request failed with status: ${response.statusCode}');
  }
}

内容的提问来源于stack exchange,提问作者Yunnane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:27:49