Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dio options.contentType vs header "Content-Type"

I was trying to make a call to a REST service using the Dio plugin, but kept getting HTTP 400 response code. I thought I was doing everything right by setting the content type and response type options to JSON:

Response response = await Dio().get(
    'https://api.example.com/v1/products/$productId',
    queryParameters: {},
    options: Options(
        contentType: ContentType.json,
        responseType: ResponseType.json,
        headers: {'Authorization': 'Bearer $MY_API_KEY'}
    ),
);

However, it turns out that I needed to add a Content-Type header as well:

headers: {'Authorization': 'Bearer $MY_API_KEY'}, 'Content-Type': 'application/json' };

So now I'm confused - what exactly does the contentType option do? I thought it was analogous to setting the Content-Type header manually?

like image 510
Magnus Avatar asked Sep 04 '26 02:09

Magnus


1 Answers

I've tried this locally using dio: ^3.0.10 and it seems that ContentType.json is an invalid value for contentType.

invalid contentType

Digging through the documentation for dio, Headers.jsonContentType should be used.

valid contentType

like image 176
Omatt Avatar answered Sep 06 '26 21:09

Omatt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!