gpt4 book ai didi

post - Flutter - 处理POST请求中的状态码302

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

我正在尝试使用 DIO 包在 Flutter 中发送一个 post 请求。

请求如下:

getSessionId() async {

var csrf = await getCsrftoken();

var dio = new Dio(new Options(
baseUrl: "http://xxxxxxx/accounts/login/",
connectTimeout: 5000,
receiveTimeout: 100000,
// 5s
headers: {
'Cookie': "csrftoken=" + csrf
},
contentType: ContentType.JSON,
// Transform the response data to a String encoded with UTF8.
// The default value is [ResponseType.JSON].
responseType: ResponseType.PLAIN
));

var response;
response = await dio.post("http://xxxxxxx/accounts/login/",
data: {
"username": "xxxxx",
"password": "xxxxx",
"csrfmiddlewaretoken" : csrf
},
options: new Options(
contentType: ContentType.parse("application/x-www-form-urlencoded")),
);

print("StatusCode: ");
print(response.statusCode);
print("Response cookie: "); //THESE ARE NOT PRINTED
print(response.headers);
}

请求后我得到:

E/flutter ( 4567): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter ( 4567): DioError [DioErrorType.RESPONSE]: Http status error [302]
E/flutter ( 4567): #0 getSessionId (file:///C:/get_order/lib/main.dart:36:14)
E/flutter ( 4567): <asynchronous suspension>

根据这个请求,我只需要获取 sessionid cookie,但是该函数因未处理的异常而停止。

最佳答案

我是这样解决的:

添加followRedirects: falsevalidateStatus: (status) { return status < 500;}到请求。像这样:

var response = await Dio().post("http://myurl",
data: requestBody,
options: Options(
followRedirects: false,
validateStatus: (status) { return status < 500; }
),
);

这样可以从302得到每个headers及其他。

关于post - Flutter - 处理POST请求中的状态码302,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52647521/

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