flutter dio 源码解析2

Future> _dispatchRequest(RequestOptions reqOpt) async {
  var cancelToken = reqOpt.cancelToken;
  ResponseBody responseBody;
  try {
    //data 转流
    var stream = await _transformData(reqOpt);
    //返回数据(下个代码块分析) 数据是以流的形式保存, 后面会转换格式
    responseBody = await httpClientAdapter.fetch(
    ...省略
    );

    responseBody.headers = responseBody.headers;
    var headers = Headers.fromMap(responseBody.headers);
    //创建Response  responseBody 给值
    var ret = Response(
      headers: headers,
      requestOptions: reqOpt,
      redirects: responseBody.redirects ?? [],
      isRedirect: responseBody.isRedirect,
      statusCode: responseBody.statusCode,
      statusMessage: responseBody.statusMessage,
      extra: responseBody.extra,
    );
    //判断状态
    var statusOk = reqOpt.validateStatus(responseBody.statusCode);
    if (statusOk || reqOpt.receiveDataWhenStatusError == true) {
      //是否需要转换
      var forceConvert = !(T == dynamic || T == String) &&
          !(reqOpt.responseType == ResponseType.bytes ||
              reqOpt.responseType == ResponseType.stream);
      String? contentType;
      if (forceConvert) {
        //设置头
        contentType = headers.value(Headers.contentTypeHeader);
        headers.set(Headers.contentTypeHeader, Headers.jsonContentType);
      }
      //实际处理者 DefaultTransformer.transformResponse 根据返回数据类型转换为具体的数据格式
      ret.data =
      (await transformer.transformResponse(reqOpt, responseBody)) as T?;
      if (forceConvert) {
        headers.set(Headers.contentTypeHeader, contentType);
      }
    } else {
      await responseBody.stream.listen(null).cancel();
    }
    //继续是否取消请求
    checkCancelled(cancelToken);
    if (statusOk) {
      //返回ret
      return checkIfNeedEnqueue(interceptors.responseLock, () => ret);
    } else {
      throw DioError(
        requestOptions: reqOpt,
        response: ret,
        error: 'Http status error [${responseBody.statusCode}]',
        type: DioErrorType.response,
      );
    }
  } catch (e) {
    throw assureDioError(e, reqOpt);
  }

分析请求

@override
Future fetch(
    RequestOptions options,
    Stream? requestStream,
    Future? cancelFuture,
    ) async {
  //创建httpClient
  var _httpClient = _configHttpClient(cancelFuture, options.connectTimeout);
  //打开链接
  var reqFuture = _httpClient.openUrl(options.method, options.uri);


  late HttpClientRequest request;
  try {
    request = await reqFuture;
    if (options.connectTimeout > 0) {
      request = await reqFuture
          .timeout(Duration(milliseconds: options.connectTimeout));
    } else {
      request = await reqFuture;
    }

    //设置 Headers
    options.headers.forEach((k, v) {
      if (v != null) request.headers.set(k, '$v');
    });
  }
  if (requestStream != null) {
    // 添加data流
    var future = request.addStream(requestStream);
    if (options.sendTimeout > 0) {
      future = future.timeout(Duration(milliseconds: options.sendTimeout));
    }
    try {
      //开始发送
      await future;
    } 
  }
  //关闭接收
  var future = request.close();
  if (options.receiveTimeout > 0) {
    future = future.timeout(Duration(milliseconds: options.receiveTimeout));
  }
  late HttpClientResponse responseStream;
  try {
    responseStream = await future;
  }
  //返回流换转
  var stream =
  responseStream.transform(StreamTransformer.fromHandlers(
...省略
  ));
return ResponseBody(
  stream,
  responseStream.statusCode,
  headers: headers,
  isRedirect:
      responseStream.isRedirect || responseStream.redirects.isNotEmpty,
  redirects: responseStream.redirects
      .map((e) => RedirectRecord(e.statusCode, e.method, e.location))
      .toList(),
  statusMessage: responseStream.reasonPhrase,
);
}

你可能感兴趣的:(flutter)