Flutter 熱門網路請求框架Dio的簡單封裝

MrDotY發表於2021-03-03
import 'dart:convert';

import 'package:dio/dio.dart';

//建立dio例項
Dio dio = new Dio();

class HttpUtils {
  HttpUtils() {
    // 在建構函式裡面新增攔截器
    dio.interceptors.add(CustomInterceptors());
  }
	//get方法 path和query引數
  Future get(path, query) async {
    Response resp;
    try {
      resp = await dio.get(path, queryParameters: query);

      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }
	//post方法
  Future post(path, data) async {
    Response resp;
    try {
      resp = await dio.post(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }

  Future put(path, data) async {
    Response resp;
    try {
      resp = await dio.put(path, data: data);
      if (resp.statusCode == 200) {
        String val = resp.toString();
        return jsonDecode(val);
      } else {
        String val = resp.toString();
        return jsonDecode(val);
      }
    } catch (error) {
      return error;
    }
  }
}

class CustomInterceptors extends InterceptorsWrapper {
//future函式,可以使用非同步設定
  @override
  Future onRequest(RequestOptions options) {
    //超時設定
    options.connectTimeout = 30000;
    options.receiveTimeout = 30000;
    //設定token
    options.headers["Authorization"] = "Bearer ";
    //設定請求頭
    options.headers['content-type'] = "application/x-www-form-urlencoded";
    
    print('------------------------請求開始------------------------');
    print('- 請求方式:${options?.method}');
    print('- 請求資料: ${options?.data}');
    print('- 請求頭資訊:${options.headers}');
    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    print('------------------------請求結束------------------------');
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    print('------------------------請求出錯------------------------');
    print('- 錯誤型別:${err.type}');
    print('- 錯誤資訊:${err.message}');
    print('- error: $err');
    return super.onError(err);
  }
}

複製程式碼

相關文章