更改 Dio 请求中的内容类型

Change content-type in Dio request

请告诉我如何使用 Dio 更改请求的内容类型?我试图通过将 contentType: Headers.formUrlEncodedContentType 添加到选项中来更改它,但它看起来无济于事。

我的代码是:

  final String urlString4 = protocol + baseUrl + '/connect/token';

  var loginBody4 = FormData.fromMap({
    'code': code,
    'grant_type': 'authorization_code',
    'redirect_uri': 'courier-mobile-app://auth/login',
    'code_verifier': 'application_application_application_application_application',
    'client_id': 'courier_mobile_app',
    'client_secret': 'secret'
  });

  try {
    response = await dio.post(urlString4,
        data: loginBody4,
        options: Options(
          contentType: Headers.formUrlEncodedContentType
        )
    );
  } on DioError catch (e) {
    print('Request failed with status: ${e.response?.data}');
  }

但是我截获的请求是这样的:

curl -H "user-agent: Dart/2.16 (dart:io)"
-H "content-type: multipart/form-data; boundary=--dio-boundary-3038081899"
-H "cookie: .AspNetCore.Antiforgery.2P6h…..h3g"
-H "host: auth.dev-drive.XXX.dev
--data-binary "----dio-boundary-3038081899
content-disposition: form-data; name=\"code\"

C8C3E5D1ACE01DF61F988E06C391AAB3347BD2A64A0B6F56E5DC225710BEF672
----dio-boundary-3038081899
content-disposition: form-data; name=\"grant_type\"

authorization_code
----dio-boundary-3038081899
content-disposition: form-data; name=\"redirect_uri\"

courier-mobile-app://auth/login
----dio-boundary-3038081899
content-disposition: form-data; name=\"code_verifier\"

application_application_application_application_application
----dio-boundary-3038081899
content-disposition: form-data; name=\"client_id\"

courier_mobile_app
----dio-boundary-3038081899
content-disposition: form-data; name=\"client_secret\"

secret
----dio-boundary-3038081899--
" --compressed "https://auth.dev-drive.XXX.dev/connect/token"

我这样试过

dio.options.headers['content-Type'] = 'application/x-www-form-urlencoded';
response = await dio.post(urlString4, data: loginBody4);

但结果是一样的:

content-type: multipart/form-data; boundary=--dio-boundary-3428087265

感谢 Anis 的建议,它奏效了!确实问题出在 FormData

  Map<String, String> loginBody4 = {
    'code': code,
    'grant_type': 'authorization_code',
    'redirect_uri': 'courier-mobile-app://auth/login',
    'code_verifier': 'application_application_application_application_application',
    'client_id': 'courier_mobile_app',
    'client_secret': 'secret'
  };

  response = await dio.post(urlString4, data: loginBody4, options: Options(contentType: Headers.formUrlEncodedContentType));

这也有效:

  dio.options.headers['content-Type'] = 'application/x-www-form-urlencoded';
  response = await dio.post(urlString4, data: loginBody4);