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

时间:2019-07-18 07:47:40

标签: api flutter dart httpclient

实际上我想在我的项目中为所有HTTP请求使用dio(Dart的Http客户端),我签入了官方文档,但无法申请。

使用来自软件包:http / http.dart的http客户端,它工作正常,但是我想与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 个答案:

答案 0 :(得分: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是必需的