flutter實用系列(五)之網絡請求dio,請求,攔截器簡單示例

flutter一直很火的網絡請求插件dio
直接上代碼,寫成一個類,能夠直接使用
包含請求的封裝,攔截器的封裝json

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文件則是放一些請求頭信息以下api

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';
相關文章
相關標籤/搜索