Unable to add header for post method in dio in Flutter
Asked Answered
D

7

49

I'm using dio: ^3.0.4. Any one please help me to find the solution for adding header. here my code:

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;
      }
    ),
  );

When i print the header.

print(response.headers);

Result:

flutter: content-type: text/html; charset=UTF-8 connection: close cache-control: no-cache, private transfer-encoding: chunked date: Thu, 07 Nov 2019 14:29:02 GMT server: Apache/2.4.18

Doubt answered 7/11, 2019 at 14:33 Comment(5)
You are printing the response headers, which look basically correct for response headers. What are you trying to print?Bertrand
@RichardHeap I try to add authorization key into header, but when i send to the server, The server can not get the header of authorization.Doubt
Check that your server accepts the header name authorization in lower case. Dart will typically lower case all header name. Use Postman to confirm that a lower case header name works.Bertrand
Just found the problem with server side checking header. It's not work with apache_request_headers() on Laravel, need to use req->request();.Doubt
It's probably best to delete this question, as the solution is not actually related to the question. Your Dart code turned out to be correct.Bertrand
P
48

Dio library key working perfectly fine in my case if we pass small case key value

For example,

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

make sure you write key in small case, that's work for me.

Pape answered 8/11, 2019 at 5:14 Comment(2)
It's not necessary to write the keys in small case. It is just case sensitive.Conglobate
I am adding header in interceptors but now the request in not forwarding any more.Nymphalid
B
22

In case of you use di in your projects and the dioclient is a singleton, this is how authorization is added to the call.

final response = await _dioClient.get(Endpoints.getDashboard,
          queryParameters{'shopId':int.parse(shopId)},
          options: Options(
            headers: {
              "authorization": "Bearer <your token>",
            },
          ),
        );
Bermejo answered 1/9, 2021 at 18:43 Comment(0)
T
17

There are some similar questions do not have answer
But the following work for me
Please use the following code snippet to set headers attribute

  Dio dio = new Dio();
  dio.options.headers["Authorization"] = "Bearer ${token}";
  response = await dio.post(url, data: data);
Tyr answered 8/11, 2019 at 4:10 Comment(1)
How to do the same thing when authorization is done using API key instead of token? @TyrOpenandshut
D
2

This work for me after try differents ways to pass the argument to headers

    Dio dio = new Dio();
    dio.options.contentType = ContentType("application","x-www-form-urlencoded");
    dio.options.headers[HttpHeaders.authorizationHeader] ="Basic $clientCredentials";
Dresser answered 2/4, 2020 at 12:1 Comment(1)
The argument type 'ContentType' can't be assigned to the parameter type 'String'.Wanwand
W
1

That's probably bug because I was not able to set it with lowercase content-type.

Content-Type works.

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

Feel free to refer to https://github.com/flutterchina/dio/issues/1045

Wanwand answered 13/2, 2021 at 17:46 Comment(0)
P
0
dio.options.contentType = ContentType("application","x-www-form-urlencoded") as String;
Palaeography answered 26/7, 2021 at 5:41 Comment(0)
E
0

I'm using it like this:

_dio = Dio();
_dio.options.baseUrl = _baseUrl;
_dio.options.connectTimeout = 5000; //5s
_dio.options.receiveTimeout = 3000;
_dio.options.contentType = 'application/json';
_dio.options.headers['Content-Type'] = 'application/json';
_dio.options.headers["Authorization"] = "Bearer 284|NRx1PaEY2HbwHi2XMzGdxg9UJ5rGXkNMcYyNXkqH";
_dio.options.followRedirects = false;
_dio.options.validateStatus = (status) {
  return status! < 500;
};
Edrisedrock answered 20/5, 2022 at 5:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.