0

我无法使用 dio 设置标头。我正在尝试将我的访问令牌设置为标头。我正在尝试设置标头,以便每个请求都不需要调用它。这是我试图调用标头的网络类带迪奥

我的网络类:

class NetworkUtil {
 Dio _dio;
String token;

  getToken() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    String getToken = preferences.getString(AppPrefernces.LOGIN_PREF);
    return getToken;
  }

  NetworkUtil() {
    ///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
    BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
    options.baseUrl = ApiConstants.BASE_URL;
    _dio = Dio(options);
    _dio.interceptors.add(InterceptorsWrapper(
        onRequest: (Options option) async{
          //my function to recovery token
          await getToken().then((result) {
            LoginResponse loginResponse = LoginResponse.fromJson(jsonDecode(result));
            token = loginResponse.accessToken;
          });
          option.headers = {
            "Authorization": "Bearer $token"
          };
        }
    ));


  }

   


  ///used for calling Get Request
  Future<Response> get(String url, Map<String, String> params) async {
    Response response = await _dio.get(url,
        queryParameters: params,
        options: Options(responseType: ResponseType.json));
    return response;
  }

  ///used for calling post Request
  Future<Response> post(String url, Map<String, String> params) async {
    Response response = await _dio.post(url,
        data: params, options: Options(responseType: ResponseType.json));
    return response;
  }
}
4

1 回答 1

0

我使用这个设置,它对我来说很好。

  Future<Dio> createDioWithHeader() async {
    if (_dioWithHeader != null) return _dioWithHeader;

    String token = await appSharedPreferences.getToken();
    String userAgent = await getUserAgent();
    print('User-Agent: $userAgent');
    // base config
    _dioWithHeader = Dio(BaseOptions(
        connectTimeout: 10000,
        receiveTimeout: 10000,
        baseUrl: Config.apiBaseUrl,
        contentType: 'application/json',
        headers: {
          'Authorization': token,
          'User-Agent': userAgent
        }));

    // setup interceptors
    return addInterceptors(_dioWithHeader);
  }```
于 2020-09-05T06:52:52.923 回答