Flutter - 处理 POST 请求中的状态代码 302 [英] Flutter - Handle status code 302 in POST request
本文介绍了Flutter - 处理 POST 请求中的状态代码 302的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 DIO
包在 Flutter 中发送 post
请求.
I'm trying to send a post
request in Flutter with DIO
package.
这是请求:
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,但该函数因未处理的异常而停止.
From this request i only need to get the sessionid
cookie, but the function stop with unhandled exception.
推荐答案
我是这样解决的:
添加 followRedirects: false
和 validateStatus: (status) { return status <;500;}
到请求.像这样:
Add followRedirects: false
and validateStatus: (status) { return status < 500;}
to the request. Like this:
var response = await Dio().post("http://myurl",
data: requestBody,
options: Options(
followRedirects: false,
validateStatus: (status) { return status < 500; }
),
);
通过这种方式,您可以从 302
中获取每个 headers
和其他.
This way you can get from the 302
every headers
and other.
这篇关于Flutter - 处理 POST 请求中的状态代码 302的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文