Reputation: 403
I'm sending a post request for my login form; using dart's HTTP library.
In its response, I have no idea how to access the header content; because that's where the token is, which I need for further operations throughout the session.
The server sends content in JSON. (I am new to this, forgive my ignorance)
My main aim is to read header content from the response I got from the POST request.
Below is the code snippet.
var jsonresponse = Map();
Future login() async{
try{
response = await http.post(
baseLog,
body: {
"username": username.text,
"password": password.text
},
);
//json decode
this.jsonresponse = json.decode(this.response);
var token = this.response.headers.get('token'); //an attempt to access the header
//print('token ' + token);
}
catch(ex){
print('Error occured' + ex);
}
}
Upvotes: 0
Views: 1854
Reputation: 81
To read headers from response its pretty easy.
var response = await http.post(
baseLog,
body: {
"username": username.text,
"password": password.text
},
);
var date = response.headers['date'];
This should get you date from response.
Upvotes: 2
Reputation: 7148
To send a post request with headers and body, you can follow the way like,
var response = await http.post(
url,
body: {
"name": "Test",
"password": "123456",
},
// you can pass headers using HttpHeaders different properties like
headers: {
// HttpHeaders has many properties like AUTHORIZATION, contentTypeHeader, acceptHeader etc. you can use them accordingly.
HttpHeaders.AUTHORIZATION: "Bearer your_token",
HttpHeaders.contentTypeHeader:"application/json"
},
OR
//Also, you can pass headers like a json object,
headers: {
"authorisation:"Bearer your_token"
"content-type":"application/json"
}
);
This is a general approach to send the post request to server.
Upvotes: 0