how to send token while post request - flutter

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

Related

Getting empty response body from a http post request to an api

This is my code. The goal is to get the link with file id.
// body parameter
Map<String, dynamic> body = {'file_id': 123};
String jsonBody = json.encode(body);
// response request
var download_response = await http.post(
Uri.parse('https://api.opensubtitles.com/api/v1/download'),
headers: {
'Content-Type': 'application/json',
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v'
},
body: jsonBody,
);
// print
debugPrint(download_response.body.toString());
I think I should be getting a JSON data response which I'm getting properly with postman but in flutter I'm getting empty response.
Things I tried:
encoding the body with jsonencode
correct syntax formatting
writing the body in plain json string
var headers = {
'Api-Key': 'yCTZwGASncUthpMkMkbQDjcUdrrM2r8v',
'Content-Type': 'application/json'
};
var request = http.MultipartRequest('POST', Uri.parse('https://api.opensubtitles.com/api/v1/download'));
request.fields.addAll({
'file_id': '123'
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}

Invalid argument(s): No host specified in URI

auth_service.dart
The following ArgumentError was thrown resolving an I/flutter (11774): Invalid argument(s): No host specified in URI
This my Code pleaseeeeeeeee help meeee
class AuthService {
String baseUrl = 'http://shamo-backend.buildwithangga.id/api';
Future<UserModel?> register({
required String name,
required String username,
required String email,
required String password,
}) async {
// ignore: unused_local_variable
var url = '$baseUrl/register';
var header = {'Content-Type': 'application/json'};
var body = jsonEncode({
'name': name,
'username': username,
'email': email,
'password': password,
});
var response = await http.post(
Uri(),
headers: header,
body: body,
);
print(response.body);
if (response.statusCode == 200) {
var data = jsonDecode(response.body)['data'];
UserModel user = UserModel.fromJson(data['user']);
// ignore: prefer_interpolation_to_compose_strings
user.token = 'Bearer ' + data['access_token'];
return user;
} else {
throw Exception('Gagal Register');
}
}
}
Iwant save like this enter image description here
Please Helpme
You are not passing any url in http.post. Replace
var response = await http.post(
Uri(),
headers: header,
body: body,
);
With
var response = await http.post(
Uri.parse(url),
headers: header,
body: body,
);
Refer this documentation for detail information
Use it like this to resove this issue
// edit this line of your code
====> var header = {'Content-Type': 'application/json'};
// with this
====> var header = {'Content-Type': 'application/json; charset=UTF-8'};
// FULL CODE
class CreateGoalModals {
Future<Add_Goal_Status> create_goal_WB(
String name,
String username,
String email,
String password,
) async {
final response = await http.post(
Uri.parse(
your_application_base_url,
),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, String>{
'name': name,
'username': username,
'email': email,
'password': password,
},
),
);
if (response.statusCode == 201) {
print('=========> 201');
print(response.body);
} else if (response.statusCode == 200) {
print('==========> 200');
print(response.body);
// after SUCCESS
if (success_text == "success") {
print('=========> SUCCESSFULLY <===========');
} else {
print('========> SUCCESS WORD FROM SERVER IS WRONG <=========');
}
// throw Exception('SOMETHING WENT WRONG. PLEASE CHECK');
} else {
print("============> ERROR");
print(response.body);
}
}
}

Flutter http.dart post request to Infura Ipfs API Response status: 400 Response body: file argument 'path' is required

I'm trying to make a post request to /api/v0/add but the server respond with the following
error message
and this is the request code:
String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
final Map body = {'file': '$path/light.txt'};
var url = Uri.https(
'ipfs.infura.io:5001',
'/api/v0/add'
);
print(url);
var response = await http.post(
url,
body: json.encode(body),
headers: <String, String>{
"Authorization": basicAuth,
}
);
print('REQUEST: ${response.request}');
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
I have olso tryed to parse the body with a string but nothing changed.
the api on postman works
api postman
In your Postman screenshot, the radio button for "Form Data" is selected. This is plain old form encoded data, yet you've JSON-encoded your map unnecessarily.
Change your code to this:
final auth = base64.encode(utf8.encode('$username:$password'));
final body = <String, String>{'file': '$path/light.txt'};
final response = await http.post(
Uri.https('ipfs.infura.io:5001', '/api/v0/add'),
body: body,
headers: <String, String>{
'Authorization': 'Basic $auth',
},
);

Can't get auth token stored in flutter secure storage to headers

I am making flutter app using API and I have a problem. When I want to get auth token to make request, flutter says that "Expected a value of type 'String', but got one of type '_Future'". How can I make a request with auth token without that error?
My login function, where I write the token:
loginUser() async {
final storage = new FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/login");
await http
.post(uri,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"username": emailController.text,
"password": passwordController.text
}))
.then((response) async {
if (response.statusCode == 200) {
var data = json.decode(response.body);
await storage.write(key: "token", value: data["token"]);
print(data["token"]);
} else {
print(json.decode(response.body));
}
});
}
My getdata function, where i use the token:
getdata() async {
final storage = FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": await storage.read(key: "token")
});
}
try this code
String token = await storage.read(key: 'token');
//make sure if there is no Bearer just token in that case just pass the token
var headers = {
'accept': 'application/json',
'Authorization': 'Bearer ${token}',
};
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
Response response = await http.get(
uri,
headers: headers
);
print (response);

how post api with authentication identifier and secret in 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