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

Dev*_*977 2 post request http-status-code-302 dart flutter

我正在尝试使用postFlutter 发送带有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);
}
Run Code Online (Sandbox Code Playgroud)

请求后,我得到:

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>
Run Code Online (Sandbox Code Playgroud)

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

A.K*_*.94 7

我遇到了类似的问题,我通过添加带有"Accept":"application/json" 的标头解决了它。此后它只会返回 json 数据,否则会提示使用 html url 重定向。


Ric*_*eap 6

除非响应代码是 303,否则Dart HTTP 客户端不会遵循POST重定向。它遵循 GET 或 HEAD 的 302 重定向。

您可以查看是否可以停止服务器发送重定向以响应(可能)有效的登录请求,并改为发送 200。

或者,您可以尝试通过将表单字段编码到 URL 中来将登录请求作为 GET 发送,例如:

http://xxxxxxx/accounts/login/?username=xxxx&password=yyyy&csrfmiddlewaretoken=zzzz

您必须对参数中的任何特殊字符进行 URL 编码。想必,您也想使用 HTTPS。

最后,URL 是否以/?结尾?或许值得一试/accounts/login。


Dev*_*977 5

我这样解决了:

在请求中添加followRedirects: false和validateStatus: (status) { return status < 500;}。像这样:

var response = await Dio().post("http://myurl",
    options: Options(
        followRedirects: false,
        validateStatus: (status) { return status < 500; }
    ),
);
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以从302彼此之间获取headers利益。

  • 可以通过在 header 中添加 Accept type 作为 application/json 来解决 (2认同)
  • “接受”:“application/json”解决了我的问题。谢谢 (2认同)