基于责任链模式实现Flutter http网络框架

Flutter 简单封装http网络框架
Flutter 实现下拉刷新和自动加载更多
Flutter Banner封装
Flutter使用官方CustomScrollView实现复杂页面下拉刷新和加载更多
Flutter之Router和Navigator实现页面跳转
Flutter的基本应用

责任链模式

责任链模式,顾名思义就是在完成某一件事的过程中,按照顺序每个单元或节点都能有机会参与到这个过程中负责自己职责内的事情。
在Android开发过程中可能大家都用到过okhttp网络请求框架,而okhttp中也是使用了责任链设计模式。

abstract interface class Interceptor {
  Future<http.Response> intercept(
  RealInterceptorChain chain, http.Request request);
}

拦截器抽线接口,其中定义了intercept方法主要是拦截器请求过程中的请求(Request)和响应(response),该方法测参数 chain 就是在这个过程中将流程进入下一个流程,也就是

定义链条 Chain

class RealInterceptorChain {
  final int index;
  final List<Interceptor> interceptors;

  RealInterceptorChain(this.index, this.interceptors);

  Future<http.Response> proceed(http.Request request) async {
//当前拦截器,如果是最后一个interceptor,则直接发送请求并返回数据,不会再调proceed。
var interceptor = interceptors[index];
var next = RealInterceptorChain(index + 1, interceptors);
var response = await interceptor.intercept(next, request);
return response;
  }
}

网络请求管理

///通过拦截器模式实现http请求
class HttpClient {
  static const _uft8decoder = Utf8Decoder();
  final List<Interceptor> userInterceptors = [];

  static HttpClient get instance => _instance;

  static final HttpClient _instance = HttpClient._internal();

  HttpClient._internal();

  addInterceptor(Interceptor interceptor) {
      userInterceptors.add(interceptor);
  }

  Future<BaseResp> sendRequest(HttpRequest request) async {
try {
  return await _sendRequest(request).timeout(request.timeout);
} catch (e) {
  debugPrintStack(stackTrace: StackTrace.current, label: "HttpClient");
  rethrow;
}
  }

  Future<BaseResp> _sendRequest(HttpRequest request) async {
final List<Interceptor> interceptors = [
  ...userInterceptors,
  HttpClientInterceptor()
];
var realInterceptorChain = RealInterceptorChain(0, interceptors);

var response = await realInterceptorChain.proceed(request);

///关于Http 请求码的处理,业务层的交由开发者执行处理
if (response.statusCode != 200) {
  throw HttpException(response.statusCode, response.body);
}

return BaseResp.fromJson(_uft8decoder.convert(response.bodyBytes));
  }
}

发起网络请求的拦截器

class HttpClientInterceptor implements Interceptor {
  final Client client = Client();

  @override
  Future<Response> intercept(
  RealInterceptorChain chain, Request request) async {
return await Response.fromStream(await client.send(request));
  }
}

定义数据模型基类

 class BaseResp<T> {
  int code = -1;
  String msg = "";
  bool _isSuccess = false;
  T? dataEntity;

  bool get isSuccess => _isSuccess;

BaseResp.fromJson(
  dynamic jsonString, T Function(dynamic parseJsonData) function) {
try {
  var jsonData = json.decode(jsonString);
  _parseJsonData(jsonData, function);
} on FormatException catch (e) {
  // 处理JSON格式异常,例如打印日志或抛出自定义异常
  print("JSON格式错误: $e");
  // 根据实际情况决定是否需要重新抛出异常或设置默认值
} catch (e) {
  // 处理其他潜在异常
  print("解析JSON时发生错误: $e");
}
}
void _parseJsonData(Map<String, dynamic> jsonData,
  T Function(dynamic parseJsonData)? function) {
// 类型安全的获取code,确保其为int类型
int? parsedCode = jsonData['code'] as int?;
if (parsedCode != null) {
  code = parsedCode;
  _isSuccess = code == 0;
} else {
  // 如果code不存在或不是预期类型,可以考虑记录日志或处理异常
}

msg = jsonData['msg'] as String? ?? "";
var data = _isSuccess ? jsonData['data'] : null;
dataEntity = data != null ? function?.call(data) : null;
  }
}

T Function(dynamic parseJsonData)? function 该参数主要是将接口返回的数据暴露出去由下层解析数据。如 (data) => HomeModel.fromJson(data):

 static Future<BaseResp<HomeModel>> fetch() async {
final url = Uri.https(HttpUrls.BASE_URL, HttpUrls.HOME_PATH);
var request = HttpRequest(HttpMethod.get, url);
final response = await HttpClient.instance
    .sendRequest(request, (data) => HomeModel.fromJson(data));
return response;
  }

HttpClient 使用

请求网络:

 static Future<HomeModel> fetch() async {
final url = Uri.https(HttpUrls.BASE_URL, HttpUrls.HOME_PATH);
var request = HttpRequest("GET", url);
final response = await HttpClient.instance.sendRequest(request);
return HomeModel.fromJson(response.data);
  }

/// 请求头拦截器

class HeaderInterceptor implements Interceptor {
  @override
  Future<Response> intercept(
  RealInterceptorChain chain, Request request) async {
request.headers["auth-token"] = "abccdcdcdddd";
return await chain.proceed(request);
  }
}

日志打印拦截器

class LoggingInterceptor implements Interceptor {
  Utf8Decoder decoder = const Utf8Decoder();

  @override
  Future<http.Response> intercept(
  RealInterceptorChain chain, Request request) async {
debugPrint("");
debugPrint("request url:${request.method} ${request.url}");

debugPrint(
    "request headers>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
request.headers.forEach((key, value) {
  debugPrint("$key: $value");
});

debugPrint(
    "request body>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
debugPrint(decoder.convert(request.bodyBytes));

debugPrint("");
debugPrint("response>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
var response = await chain.proceed(request);

debugPrint("response statusCode:${response.statusCode}");

debugPrint("response headers:");
response.headers.forEach((key, value) {
  debugPrint("$key: $value");
});

debugPrint(
    "response body>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
debugPrint(decoder.convert(response.bodyBytes));
return response;
  }
}

添加拦截器

 HttpClient.instance.addInterceptor(HeaderInterceptor());
 HttpClient.instance.addNetInterceptor(LoggingInterceptor());

今天梳理gzip和header相关的拦截器

class BridgeInterceptor implements Interceptor {
  /// 只有当请求体大于1KB时才启用gzip压缩
  static const int compressionThreshold = 1024;
  static const String headerUserAgent = "flutter/http";
  static const String headerKeepAlive = "Keep-Alive";
  static const String headerGzip = "gzip";

  @override
  Future<Response> intercept(
  RealInterceptorChain chain, Request request) async {
/// 检查并设置accept-encoding,避免覆盖已存在的值
var transparentGzip = false;
if (!request.headers.containsKey(HttpHeaders.acceptEncodingHeader) &&
    !request.headers.containsKey(HttpHeaders.rangeHeader)) {
  transparentGzip = true;
  request.headers[HttpHeaders.acceptEncodingHeader] = headerGzip;
}

if (!request.headers.containsKey(HttpHeaders.userAgentHeader)) {
  request.headers[HttpHeaders.userAgentHeader] = headerUserAgent;
}

if (!request.headers.containsKey(HttpHeaders.hostHeader)) {
  request.headers[HttpHeaders.hostHeader] = request.url.host;
}

if (!request.headers.containsKey(HttpHeaders.connectionHeader)) {
  request.headers[HttpHeaders.connectionHeader] = headerKeepAlive;
}

var contentLength = request.bodyBytes.lengthInBytes;

///边界条件处理:对contentLength进行了更严格的检查,确保其不为负。当内容长度为0时,明确设置Content-Length头为"0"。
if (contentLength >= 0) {
  /// 优化了对contentLength的检查
  if (contentLength <= 0) {
    request.headers[HttpHeaders.contentLengthHeader] =
        contentLength.toString();
    request.headers.remove(HttpHeaders.transferEncodingHeader);
  } else {
    request.headers[HttpHeaders.transferEncodingHeader] = "chunked";
    request.headers.remove(HttpHeaders.contentLengthHeader);
  }
}

/// 根据请求体大小决定是否启用gzip压缩
if (request.bodyBytes.lengthInBytes > compressionThreshold) {
  try {
    request.bodyBytes = gzip.encode(request.bodyBytes);
  } catch (e) {
    /// 处理gzip编码时可能出现的异常,例如记录日志或抛出自定义异常
    throw Exception("Failed to gzip encode request: $e");
  }
}

var response = await chain.proceed(request);

/// 检查Content-Encoding以确认是否需要解压缩
if (transparentGzip &&
    response.headers[HttpHeaders.contentEncodingHeader] == headerGzip) {
  try {
    /// 对响应体进行gzip解压缩
    return Response.fromStream(StreamedResponse(
        Stream.value(gzip.decode(response.bodyBytes)), response.statusCode,
        headers: response.headers,
        isRedirect: response.isRedirect,
        persistentConnection: response.persistentConnection,
        reasonPhrase: response.reasonPhrase));
  } catch (e) {
    /// 处理gzip解码时可能出现的异常,例如记录日志或抛出自定义异常
    throw Exception("Failed to gzip decode response: $e");
  }
}

/// 如果响应未被gzip压缩,则直接返回
return response;
}
}

BridgeInterceptor 拦截器主要是处理了gzip和header相关的拦截器。

目前拦截器只能添加应用拦截器,比如重定向和重试等网络拦截器这种需要执行多次的拦截器,后面会补全文章.......................

可以看到,我们将整个请求过程通过责任链模式进行了分层管理,有利于后期拓展和维护,后期可以引入 gzip 和 缓存。很类似Okhttp的做法,毕竟Okhttp凝聚了很多大佬的思想。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容