gpt4 book ai didi

rest - 如何在 Flutter 网络调用中添加动态 HTTP header

转载 作者:IT王子 更新时间:2023-10-29 07:02:39 26 4
gpt4 key购买 nike

我必须从登录 API 响应中获取“cookie” header 并将其用于其他 API。

我能够从 http.Response 获取 header 值

像这样

var cookie = loginResponsehttp.headers.keys.firstWhere(
(k) => loginResponsehttp.headers[k] == 'cookie',
orElse: () => null);

但现在我想在未来的 API 调用中动态添加此 header 值。 (将在登录后调用 API)

最佳答案

只需创建一个带有自定义方法的 API 类即可执行请求并将 cookie 存储在类中。

基本实现(改编自工作代码,删除和简化的内容):

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);
}
}
}

关于rest - 如何在 Flutter 网络调用中添加动态 HTTP header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56824429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com