How to add Dynamic HTTP headers in Flutter Network Calls
896
Just create an API class with a custom method to do the requests and store the cookie in the class.
bare bones implementation (adapted from working code, things removed and simplified):
class MyApi {
String myCookie;
Future<bool> loginUser({@required String username, @required String password}) {
// THIS must be the return point, because we are returning a future!!!
return this.apiRequest(method: 'post', url: 'http://example.com/api/login', params: {'user': username, 'password':password})
.then( (response) {
if (response.statusCode == 200) {
// GET THE COOKIE HERE
myCookie = response.headers.keys.firstWhere((k) => loginResponsehttp.headers[k] == 'cookie', orElse: () => null);
}
}
Future<http.Response> apiRequest({
@required String url,
dynamic params}) async {
// separate in to get an all
if(method == 'get') {
return http.get(url, headers: {'X-Auth': myCookie, 'Content-Type': 'application/json'});
} else if (method == 'post') {
return http.post(url, body: json.encode(params), headers: {'X-Auth': myCookie, "Content-Type": 'application/json'});
} else {
// ERROR!!! throw exception?
throw Exception('Unknown http method: ' + method);
}
}
}
Author by
Developine
Visit my Blog for Programming Tutorials - Developine.com
Updated on December 12, 2022Comments
-
Developine over 1 year
I have to get 'cookie' header from Login API response and use that in other API's.
I am able to get header value from http.Response
Like this
var cookie = loginResponsehttp.headers.keys.firstWhere( (k) => loginResponsehttp.headers[k] == 'cookie', orElse: () => null);
But Now I want to dynamically add this header value in future API calls. (API calls which will be after login)
-
Developine almost 5 yearsBrother this is not a good solution, saving cookie value in a variable and using in the next request. I can do that easily, any elegant solution?