Issue
I am facing problem while converting cURL to flutter http post.
Below is the cURL code available
curl -X POST url
-u <YOUR_KEY_ID>:<YOUR_SECRET>
-H 'content-type:application/json'
-d '{ "amount": 50000, "currency": "INR", "receipt": "rcptid_11"}'
Below is the code that I have rewritten in flutter with the help of flutter documentaion.
Future<Album> createAlbum() async{
final response = await http.post(
Uri.parse('url'),
headers: {
HttpHeaders.authorizationHeader: '<$_key>:<$_secretKey>',
HttpHeaders.contentTypeHeader: 'application/json',
},
body: jsonEncode(<String, String>{
"amount": (amount*100).toString(),
"currency": "INR",
"receipt": date,
}),
);
if (response.statusCode == 201) {
print('Success');
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
All the parameters are defined in the class and used in createAlbum method. http post fails to send data.
Thanks!
Solution
You need to base64 encode the basic auth and put the string Basic
before the user:password:
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$_key:$_secretKey'));
Then use this for the auth header:
// ...
HttpHeaders.authorizationHeader: basicAuth,
Answered By - Stuck