一尘不染

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

flutter

我试图post在Flutter中发送带有DIO包装的请求。

这是请求:

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>

从此请求中,我只需要获取sessionidcookie,但是该函数会因未处理的异常而停止。


阅读 1434

收藏
2020-08-13

共1个答案

一尘不染

我这样解决了:

在请求中添加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

2020-08-13