flutter Network Request dio Request Interceptor Simple Example

  • 2021-11-10 10:38:41
  • OfStack

flutter1 is a very popular network request plug-in dio

Directly on the code, written as a class, can be directly used

Encapsulation containing requests, encapsulation of interceptors


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();
  // Request part 
  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(" Interface exception R");
      }
    }catch(e){
      print(" Network error ${e}");
    }
  }
  // Interceptor section 
  static tokenInter(){
    dio.interceptors.add(InterceptorsWrapper(
      onRequest:(RequestOptions options){
        //  Do it before sending the request 1 Some pretreatment 
        // My side arrived before sending SharedPreferences (Local storage) token And then add it to the request header 
        //dio.lock() It is to lock the request not to be sent out first, and then add the whole value to the request header dio.unlock() Unlock and send it out 
        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) {
        //  Do before returning the response data 1 Some pretreatment 
        return response; // continue
      },
      onError: (DioError e) {
        //  Do when the request fails 1 Some pretreatment 
        return e;//continue
      }
    ));
  }
}

httpHeaders file is to put some request header information as follows


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

The apidomain file contains the address information of api as follows


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

Related articles: