您好,登錄后才能下訂單哦!
flutter一直很火的網(wǎng)絡(luò)請求插件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("網(wǎng)絡(luò)出現(xiàn)錯誤${e}"); } } //攔截器部分 static tokenInter(){ dio.interceptors.add(InterceptorsWrapper( onRequest:(RequestOptions options){ // 在發(fā)送請求之前做一些預(yù)處理 //我這邊是在發(fā)送前到SharedPreferences(本地存儲)中取出token的值,然后添加到請求頭中 //dio.lock()是先鎖定請求不發(fā)送出去,當(dāng)整個取值添加到請求頭后再dio.unlock()解鎖發(fā)送出去 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) { // 在返回響應(yīng)數(shù)據(jù)之前做一些預(yù)處理 return response; // continue }, onError: (DioError e) { // 當(dāng)請求失敗時做一些預(yù)處理 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';
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。