Dio(Dart 的 Http 客户端)获取请求不适用于拦截器

Posted

技术标签:

【中文标题】Dio(Dart 的 Http 客户端)获取请求不适用于拦截器【英文标题】:Dio (Http client for Dart) get request is not working with interceptors 【发布时间】:2019-11-27 02:16:25 【问题描述】:

实际上我想在我的项目中使用 dio(Dart 的 Http 客户端)来处理所有 http 请求,我查看了官方文档但无法申请。

使用包中的 http 客户端:http/http.dart 它运行良好,但我想与 Dio 一起使用。任何人都可以检查并帮助我,为什么它不起作用。提前致谢!

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:thunder_mobile/models/login_modal.dart';
import 'package:thunder_mobile/utils/all_shared_preference_helper.dart';
import 'package:thunder_mobile/utils/http.dart';
import 'package:dio/dio.dart';

class ApiHelper 
//  Dio _dio = new Dio();
var url = "http://5c9db1fd3be4e30014a7d3da.mockapi.io/";

final thunderBaseUrl = 'https://domain/api/v1/';

var headers = 'Content-Type': 'application/json';

String token;

var sharedPref = new AllSharedPreferenceHelper();

var thunderHeaders = 
 'content-type': 'application/json',
 'x-requested-with': 'XMLHttpRequest',
;

var thunderImageHeaders = 
 'content-type': 'multipart/form-data',
 'x-requested-with': 'XMLHttpRequest',
;

final loginHeader = 'X-Requested-With': 'XMLHttpRequest';

setApiHeader() 
 sharedPref.getLoginData().then((res) 
   LoginModel loginData = LoginModel.fromJson(json.decode(res));
   if (loginData.accessToken != null) 
     thunderHeaders['authorization'] = 'Bearer ' + loginData.accessToken;
     token = loginData.accessToken;
   
 );


// --------------------http BASED (Working Successfully)--------------------------------------

Future getThunderRequest(apiUrl) async 
 await setApiHeader();
 final http.Response response =
     await http.get(thunderBaseUrl + apiUrl, headers: thunderHeaders);
 return response;


Future postThunderRequest(apiUrl, body) async 
 await setApiHeader();
 final response = await http.post(thunderBaseUrl + apiUrl,
     headers: thunderHeaders, body: json.encode(body.toJson()));
 return response;


// ----------------------DIO API'S(not Working)------------------------------------

Future getDioRequest(apiUrl) async 
 Dio dio = new Dio();
 dio.interceptors
     .add(InterceptorsWrapper(onRequest: (RequestOptions options) async 
   await setApiHeader();
   options.headers["token"] = thunderHeaders;
   return options;
 ));
 try 
   Response response = await Dio().get('https://domain/api/v1/master');
   print(response);
  catch (e) 
   print(e);
 
```

【问题讨论】:

【参考方案1】:

更新

dio = Dio();
dio.options.baseUrl = URL_API_PROD;
dio.interceptors.add(InterceptorsWrapper(
  onRequest: (Options option) async
    //my function to recovery token
    await getToken().then((result) 
      token = result;
    );
    option.headers = 
      "Authorization": "Bearer $token"
    ;
  
));
//here i use the dio instance on constuctor and call the get verb to get the data
Future<List<Children>> getChildren() async 
    Response response = await dio.get('/v1/pessoa/alunosresponsavel');
    //here I map the json from response to my model(children)
    return (response.data['Dados'] as List).map((child)=> Children.fromJson(child)).toList();
  

getToken.dart

import 'package:shared_preferences/shared_preferences.dart';

getToken() async 
  SharedPreferences preferences = await SharedPreferences.getInstance();
  String getToken = preferences.getString("LastToken");
  return getToken;

PS-> 依赖shared_preferences 是必须的

【讨论】:

谢谢你!并请分享您调用获取请求的位置以及使用拦截器的位置..再次感谢您的回复.. 我收到 DioError [DioErrorType.RESPONSE]: XMLHttpRequest error when added header to the dio request using this method

以上是关于Dio(Dart 的 Http 客户端)获取请求不适用于拦截器的主要内容,如果未能解决你的问题,请参考以下文章

Flutter进行HTTP请求并保存登陆状态(dio)

Flutter进行HTTP请求并保存登陆状态(dio)

Flutter进行HTTP请求并保存登陆状态(dio)

Flutter 之网络请求Dio, FormData, 表单网络请求, x-www-form-urlencoded

Dio 泛型网络请求封装。带基类。带完整日志输出

dart - 如何使用 http.post 实时获取我的数据?