詳解flutter之網絡請求dio,請求,攔截器簡單示例

這篇文章主要介紹了詳解flutter之網絡請求dio,請求,攔截器簡單示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

flutter一直很火的網絡請求插件dio

直接上代碼,寫成一個類,可以直接使用

包含請求的封裝,攔截器的封裝

import 'package:dio/dio.dart';
import 'dart:async';
import 'dart:io';
import './apidomain.dart';
import './httpHeaders.dart';
import 'package:shared_preferences/shared_preferences.dart';
class DioUtil{
  static Dio dio = new Dio();
  //請求部分
  static Future request(url,{formData})async{
    try{
      Response response;
      dio.options.headers = httpHeaders;
      dio.options.contentType = ContentType.parse("application/json;charset=UTF-8");
      if(formData == null){
        response = await dio.post(serviceUrl+url);
      }else{
        response = await dio.post(serviceUrl+url,data:formData);
      }
      if(response.statusCode == 200){
        return response;
      }else{
        throw Exception("接口異常R");
      }
    }catch(e){
      print("網絡出現錯誤${e}");
    }
  }
  //攔截器部分
  static tokenInter(){
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        // 在發送請求之前做一些預處理
        //我這邊是在發送前到SharedPreferences(本地存儲)中取出token的值,然後添加到請求頭中
        //dio.lock()是先鎖定請求不發送出去,當整個取值添加到請求頭後再dio.unlock()解鎖發送出去
        dio.lock();
        Future<dynamic> future = Future(()async{
          SharedPreferences prefs =await SharedPreferences.getInstance();
          return prefs.getString("loginToken");
        });
        return future.then((value) {
          options.headers["Authorization"] = value;
          return options;
        }).whenComplete(() => dio.unlock()); // unlock the dio
      },
      onResponse:(Response response) {
        // 在返回響應數據之前做一些預處理
        return response; // continue
      },
      onError: (DioError e) {
        // 當請求失敗時做一些預處理
        return e;//continue
      }
    ));
  }
}

httpHeaders文件則是放一些請求頭信息如下

const httpHeaders={
  'Accept': 'application/json, text/plain, */*',
  'Authorization': '666',
  'Content-Type': 'application/json;charset=UTF-8',
  'Origin': 'http://localhost:8080',
  'Referer': 'http://localhost:8080/',
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
};

apidomain文件則是放api的地址信息如下

const serviceUrl = 'http://39.xxx.xxx.xx:8080';

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章