23

我正在使用dio: ^3.0.4。任何人请帮我找到添加标题的解决方案。这是我的代码:

FormData formData = 
    new FormData.fromMap({"files": await MultipartFile.fromFile(filePath.path, filename: 'photo')
          });

  Response response = await dio.post("***********",
    data: formData,
    onSendProgress: (int sent, int total) {
      print("$sent $total");
    },
    options: Options(
      headers: {
        "authorization": "*************"
      },
      followRedirects: false,
      validateStatus: (status) {
        return status <= 500;
      }
    ),
  );

当我打印标题时。

打印(response.headers);

结果:

颤振:内容类型:文本/html;charset=UTF-8 连接:关闭缓存控制:无缓存,私有传输编码:分块日期:2019 年 11 月 7 日星期四 14:29:02 GMT 服务器:Apache/2.4.18

4

6 回答 6

27

如果我们传递小写键值,Dio 库键在我的情况下工作得很好

例如,

Dio dio = new Dio();
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "token ${token}";
response = await dio.post(url, data: data);                                                      

确保你用小写字母写钥匙,这对我有用。

于 2019-11-08T05:14:33.383 回答
14

有一些类似的问题没有答案
但以下工作对我来说
请使用以下代码片段设置标题属性

  Dio dio = new Dio();
  dio.options.headers["Authorization"] = "Bearer ${token}";
  response = await dio.post(url, data: data);
于 2019-11-08T04:10:15.230 回答
2

在尝试不同的方法将参数传递给标题后,这对我有用

    Dio dio = new Dio();
    dio.options.contentType = ContentType("application","x-www-form-urlencoded");
    dio.options.headers[HttpHeaders.authorizationHeader] ="Basic $clientCredentials";
于 2020-04-02T12:01:50.180 回答
1

如果您在项目中使用 di 并且 dioclient 是单例,这就是将授权添加到调用的方式。

final response = await _dioClient.get(Endpoints.getDashboard,
          queryParameters{'shopId':int.parse(shopId)},
          options: Options(
            headers: {
              "authorization": "Bearer <your token>",
            },
          ),
        );
于 2021-09-01T18:43:27.367 回答
0

这可能是错误,因为我无法用小写设置它content-type

Content-Type作品。

options.headers = {'Content-Type': 'application/json', ...request.headers};

随意参考https://github.com/flutterchina/dio/issues/1045

于 2021-02-13T17:46:49.417 回答
0
dio.options.contentType = ContentType("application","x-www-form-urlencoded") as String;
于 2021-07-26T05:41:12.823 回答