how post api with authentication identifier and secret in flutter - flutter

i want fetch data by post method with identifier and secret in flutter
where should i add "identifier" and "secret" in post method?
in postman they added to body and that works but i couldnt add these to flutter code:
Future post(String url, var data) async {
String url = 'https://member.example.com/includes/api.php';
var data = {
'identifier': 'identifier code otm7LE8OzlBmprXn',
'secret': 'secret code SXZgmDpX8miT31PSRQ',
'action': 'GetInvoices',
'userid': 6414,
'orderby': 'date',
'responstype': 'json',
};
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
},
body: jsonEncode(data),
);
} catch (e) {
print(e);
}
}
E/flutter ( 6118): result=error;message=Authentication Failed

Related

how to send token while post request

have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....
here is my token, which i received after login as response
{
"token": "8d18265645a87d608868a127f373558ac2e131a6"
}
Here, i have to implement in flutter
apiData.ApiData app = apiData.ApiData();
final String apiURl = app.api;
SharedPreferences pref = await SharedPreferences.getInstance();
String? email = pref.getString("useremail");
String? token = pref.getString('token');
String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
String time = DateFormat("Hms").format(DateTime.now());
print(time);
print(date);
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
'user': email,
'start_time': time,
'start_date': date,
});`
Here in the documentation you can found the following snippet, where the headers are sent with the HTTP request:
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
Add header in the post method as below:
var headers = {
'authorization': token,
"Accept": "application/json"
};
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"),headers: headers), body: {
...
});
final response = await http.get(
Uri.parse(apiURl + "/api/user-log/"),
body: {}
headers: {
HttpHeaders.authorizationHeader: "<Your token here>",
},
);
Documentation here

When I use flutter http library with headers authorization token, its shows 500, in console. but in postman all okay

Here is my code, I also tried using retrofit but I failed and it shows 500 and "message": "Undefined index: token". but in postman, it shows 200. how can it be possible?
Also tried
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
Future getCertificateList() async {
final url = Uri.parse(
'https://portal-api.jomakhata.com/api/getCertificateList');
final response = await http.get(url,
headers: {
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiY',
},
);
print(response.statusCode);
print(response.body);
return response.body;
}
In my console it's print 500
this is postman request image
try this code:
Future getCertificateList() async {
final uri = Uri.https('https://portal-api.jomakhata.com','/api/getCertificateList');
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader:
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiYv',
HttpHeaders.contentTypeHeader: 'application/json',
});
print(response.statusCode);
print(response.body);
return response.body;
}

How can I make an http POST request from dart with authentication?

I'm trying to do a post, to create a user, but in a simple way. I do need to use authentication, so I'm passing the token in the header, as I would do in the GET request. But I'm not sure why I'm receiving the error "400 - Bad Request".
import 'package:http/http.dart';
{...}
Future test() async {
Response response = await post('https://access.altaviu.com/Data/api/Account/Register',
body: jsonEncode({
"Email": "useruser#gmail.com",
"Password": "QWERTY1234!",
"ConfirmPassword": "QWERTY1234!",
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${UserAccountData.token}',
});
if (response.statusCode == 200) {
print('SUCCESSFUL TEST');
} else {
print('ERROR IN THE TEST ${response.statusCode} - ${response.reasonPhrase}');
}
}
I'm using the library (or package) "http: 0.12.0+2"

How to send parameters in headers using http package in flutter

I want to sent my auth-key in headers using http package but unfortunately its not working kindly help me .
var url = "https://paysafemoney.com/psmApi/Psm/userDashboard";
var response = await http.post(
url,
headers: {
"auth-key": LoginConfirmActivity.authKey,
},
body: sendLoginData,
);
print("Response = ${response.body}");
You can do like this
var fullUrl = '$stripeBaseUrl$customerId/sources?source=$cardToken';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': stripeKey,
};
final response = await client.post(fullUrl, headers: header);

Posting Images using formData to a Django Rest API

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.
The POST method used is as follows:
async saveUserData() {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
var formData = new FormData();
formData.append("bio",this.state.bio);
formData.append("website",this.state.website);
formData.append("phoneno",this.state.phoneno);
formData.append("gender",this.state.gender);
formData.append("avatar",this.state.avatar.uri);
try {
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
let responseJson = await response.text();
if(response.status>=200&&response.status<300){
console.log("POST Completed");
}else{
let error=responseJson;
console.log(error);
throw error;
}
return responseJson;
} catch(error) {
return error;
console.error(error);
}
}
I get the following error
{"avatar":["The submitted data was not a file. Check the encoding type on the form."]}
I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?
Here is how you can do it:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});