如何将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 whatencodeURIdoes 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.encodecombined withutf8.encode: JavaScript'sbtoaworks with ASCII strings, so in Dart we first convert the credentials string to UTF-8 bytes (usingutf8.encode) before base64 encoding it. This aligns perfectly with the original code's behavior sinceencodeURIoutputs 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
相关产品推荐
相关产品推荐

