温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解flutter之网络请求dio,请求,拦截器简单示例

发布时间:2020-10-04 21:01:36 来源:脚本之家 阅读:649 作者:的的的1995 栏目:移动开发

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';

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI