flutter项目实战三:封装http工具类

在这里插入图片描述

创建http开发目录

Api.dart为接口地址
custom_Interceptors.dart 为拦截器
http_utils.dart 为实际的http工具类

  • 统一header
  • sendTimeout 发送超时
  • receiveTimeout 接收超时
  • get请求方式
  • post请求凡是
  • form表单请求方式
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:mianzu_null_safety/http/Api.dart';

import 'custom_Interceptors.dart';
late Dio dio;
class HttpUtil{
  static HttpUtil get instance=>_getInstance();
  static HttpUtil? _httpUtil;
  static HttpUtil _getInstance(){
    return _httpUtil??HttpUtil();
  }
  getHeader(){
    return {
      'Accept': 'application/json, text/plain, */*',
      'Content-Type': 'multipart/form-data',
      'Authorization': "*",
      'User-Aagent': "4.1.0;android;6.0.1;default;A001",
      "HZUID": "2",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers":true
    };
  }

  HttpUtil(){
    dio = Dio();
    dio.options..baseUrl = Api.BASE_URL
    ..sendTimeout=5000
    ..receiveTimeout=5000
    ..validateStatus = (int ? status){
      return status!=null&&status>0;
    }
    ..headers=getHeader();

    dio.interceptors
      // ..add(LogInterceptor())
      ..add(CustomInterceptors());
  }

  Future get(String url,{Map<String,dynamic>? parameters,Options? options}) async{
    Response response;
    if(parameters!=null&&options!=null){
      response = await dio.get(url,queryParameters: parameters,options: options);
    }else if (parameters != null && options == null) {
      response = await dio.get(url, queryParameters: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.get(url, options: options);
    } else {
      response = await dio.get(url);
    }
    return response;
  }
  ///post
  Future post(String url, {required Map<String, dynamic>? parameters, Options? options}) async {
    Response response;
    if (parameters != null && options != null) {
      response = await dio.post(url, data: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.post(url, data: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.post(url, options: options);
    } else {
      response = await dio.post(url);
    }
    return response;
  }
  ///表单请求
  Future postFormData(String url, {required FormData? parameters, Options? options}) async {
    Response response;
    if (parameters != null && options != null) {
      response = await dio.post(url, data: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.post(url, data: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.post(url, options: options);
    } else {
      response = await dio.post(url);
    }
    return response;
  }
}


拦截器
  • 在http_utils 中添加 (可在拦截器中动态配置header信息)
import 'package:dio/dio.dart';
import 'package:mianzu_null_safety/constant/constant.dart';
import 'package:mianzu_null_safety/utils/log_utils.dart';
import 'package:mianzu_null_safety/utils/share_preference_utils.dart';
class CustomInterceptors extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    SharePreferenceUtils.getShareData(Constant.username).then((value) => {
      options.headers.addAll({"authorization":value??""}),
    });
    LogUtils.logInfo('CustomInterceptors onRequest PATH:=[${options.path}]\nHEADERS:=[${options.headers}]\nREQUEST:=[${options.method}]');
    return super.onRequest(options, handler);
  }
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    LogUtils.logInfo('CustomInterceptors onResponse PATH:=[${response.requestOptions.path}]\n=> statusCode:=[${response.statusCode}]\n=>data:=[${response.data}]');
    super.onResponse(response, handler);
  }
  @override
  // Future onError(DioError err, ErrorInterceptorHandler handler) {
  void onError(DioError err, ErrorInterceptorHandler handler) {
    LogUtils.logInfo('CustomInterceptors ERROR[${err.response?.statusCode}]\nPATH: ${err.requestOptions.path}');
    return handler.next(err);
  }
}

Api统一配置

class Api{
  static const String IMG_URL = 'https://mianzu.eatandshow.com/';
  static const String BASE_URL = 'https://mianzu.eatandshow.com';
  static const String REGISTER_URL=BASE_URL+'/admin.php/Admin/register';//用户注册
  static const String LOGIN_URL=BASE_URL+'/admin.php/Admin/tologin';//用户登录
  static const String UPDATEUSER=BASE_URL+'/admin.php/Admin/updateuser';//更新用户信息
  static const String GETUSERINFO=BASE_URL+'/admin.php/Admin/getuserinfo';//获取用户信息
  static const String SENDHOUSE=BASE_URL+'/admin.php/House/sendHouse';//房东发布house
  static const String FINDHOUSE=BASE_URL+'/admin.php/House/findhouse';//查询所有house列表
  static const String HOTHOUSE=BASE_URL+'/admin.php/House/hothouse';//热度值最高前三house
  static const String HOUSEDETAIL=BASE_URL+'/admin.php/House/houseDetail';//房间招租详情
  static const String INTENTIONHOUSE=BASE_URL+'/admin.php/Rent_House/intentionhouse';//租客意向房源
  static const String FIND_LIKE_HOUSE=BASE_URL+'/admin.php/Rent_House/find_like_house';//喜欢房源
  static const String SENDRENTHOUSE=BASE_URL+'/admin.php/Rent_House/sendRentHouse';//租客发布求租意向
  static const String FIND_RENT_HOUSE=BASE_URL+'/admin.php/Rent_House/find_rent_house';//查询租客发布
  static const String TOP_THREE_HOT_RENT_HOUSE=BASE_URL+'/admin.php/Rent_House/top_three_hot_rent_house';//查询租客发布前三热门
  static const String RENT_HOUSEDETAIL=BASE_URL+'/admin.php/Rent_House/rent_house_detail';//查询租客意向单详情
  static const String MAINCONTENT=BASE_URL+'/admin.php/Main_Home/mainContent';//首页banner+icon
  static const String MYHOUSE=BASE_URL+'/admin.php/House/myHouse';//我的房源
  static const String LIKERENTUSER=BASE_URL+'/admin.php/Rent_House/likeRentUser';//是否喜欢求租者
  static const String ALL_SKILL=BASE_URL+'/admin.php/Skill/skill';//所有租房技能标签
  static const String FEEDBACK=BASE_URL+'/admin.php/Feed_Back/feedback';//反馈
  static const String CHECK_UPDATE=BASE_URL+'/admin.php/Main_Home/check_update';//app检查更新
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有时有晌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值