多种网络请求方式 ,这么骚气的操作确定不来看看嘛?

前言:

兄弟们,网络真是个好东西,里面去个个都是人才,说话又好听,超喜欢在里面。
在这里插入图片描述

确实,网络已经是我们日常生活中密不可分的一部分了

那咱们今天就来讲讲Flutter里的网络。

本节内容:

1.Dart 原生的网络请求 HttpClient
2.第三方网络请求 http
3.Flutter 发布的 dio (这个可是不得了)

img

1.Dart 原生的网络请求 HttpClient

对于初学者来说,使用dart 中的HttpClient发起的请求,能快速接入HTTP网络请求。

HttpClient本身功能较弱,很多常用功能都不支持。

第一步:导入dart:io包
import 'dart:io';
第二步:创建一个HttpClient
HttpClient httpClient = new HttpClient();

该 httpClient支持常用的HTTP操作: such as GET, POST, PUT, DELETE.

第三步:打开Http连接,设置请求头
Uri uri=Uri(scheme: "https", host: "flutterchina.club", queryParameters: {
    "userName":"chen",
    "password":"123456"
  }); //在这里可以设置比如 Get 请求、Post 请求、Delete 请求

HttpClientRequest request = await httpClient.getUrl(uri);
第四步:等待连接服务器(异步请求哦)
HttpClientResponse response = await request.close();
第五步:读取响应内容
if (response.statusCode == HttpStatus.ok) {
      _content = await response.transform(Utf8Decoder()).join();
}
第六步:断开连接
httpClient.close();

这是最简单的方法,但是过于麻烦,还有 Cookie 的管理也是比较困难的

2.第三方网络请求 http

第一步:安装 http

参考:https://pub.flutter-io.cn/packages/http

http: ^0.12.2

在pubspec.yaml中配置保存后,记得put get~

Get 请求

void getRequest() async {
    var client = http.Client();
    http.Response response = await client.get(url_2);
    _content = response.body;
  }

Post 请求

  void postRequest() async {
    var params = Map<String, String>();
    params["username"] = "hellonews";
    params["password"] = "123456";

    var client = http.Client();
    var response = await client.post(url_post, body: params);
    _content = response.body;
  }

其实说了这么多作用不大,毕竟开发追求的效率

之间上压轴好戏!!!

3.dio请求

官网最新版和文档:https://pub.flutter-io.cn/packages/dio

dependencies:
  dio: ^4.0.0 

咱们先来一个简单的例子

import 'package:dio/dio.dart';

void main() async {
  var dio = Dio();
  final response = await dio.get('https://www.baidu.com');
  print(response.data);
}

这样肯定是不符合我们的开发日常需求的

我们来进行封装

dio的封装:

记得自己把包导入啊!!!,本节使用的是4.0.0的dio版本~

const int _connectTimeout = 15000; //15s
const int _receiveTimeout = 15000;
const int _sendTimeout = 10000;

typedef Success<T> = Function(T data);
typedef Fail = Function(int code, String msg);
class DioUtils {
  // default options
  static const String TOKEN = '';

  static Dio _dio;

  // 创建 dio 实例对象
  static Dio createInstance() {
    if (_dio == null) {
      /// 全局属性:请求前缀、连接超时时间、响应超时时间
      var options = BaseOptions(
        /// 请求的Content-Type,默认值是"application/json; charset=utf-8".
        /// 如果您想以"application/x-www-form-urlencoded"格式编码请求数据,
        /// 可以设置此选项为 `Headers.formUrlEncodedContentType`,  这样[Dio]就会自动编码请求体.
//        contentType: Headers.formUrlEncodedContentType, // 适用于post form表单提交
        responseType: ResponseType.json,
        validateStatus: (status) {
          // 不使用http状态码判断状态,使用AdapterInterceptor来处理(适用于标准REST风格)
          return true;
        },
        baseUrl: APIs.apiPrefix,
//        headers: httpHeaders,
        connectTimeout: _connectTimeout,
        receiveTimeout: _receiveTimeout,
        sendTimeout: _sendTimeout,
      );
      _dio = new Dio(options);
    }
    return _dio;
  }

  // 清空 dio 对象
  static clear() {
    _dio = null;
  }

  // 请求,返回参数为 T
  // method:请求方法,Method.POST等
  // path:请求地址
  // params:请求参数
  // success:请求成功回调
  // error:请求失败回调
  static Future request<T>(Method method, String path, dynamic params,
      {Success success, Fail fail}) async {
    try {
      //没有网络
      var connectivityResult = await (new Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        _onError(ExceptionHandle.net_error, '网络异常,请检查你的网络!', fail);
        return;
      }
      Dio _dio = createInstance();
      Response response = await _dio.request(path,
          data: params, options: Options(method: MethodValues[method]));
      if (response != null) {
        if (success != null) {
          success(response.data);
        }
      } else {
        _onError(ExceptionHandle.unknown_error, '未知错误', fail);
      }
    } on DioError catch (e) {
//      LogUtils.print_('请求出错:' + e.toString());
      final NetError netError = ExceptionHandle.handleException(e);
      _onError(netError.code, netError.msg, fail);
    }
  }
}

/// 自定义Header
Map<String, dynamic> httpHeaders = {
  'Accept': 'application/json,*/*',
  'Content-Type': 'application/json',
  'token': DioUtils.TOKEN
};

void _onError(int code, String msg, Fail fail) {
  if (code == null) {
    code = ExceptionHandle.unknown_error;
    msg = '未知异常';
  }
  LogUtils.print_('接口请求异常: code: $code, msg: $msg');
  if (fail != null) {
    fail(code, msg);
  }
}

Map<String, dynamic> parseData(String data) {
  return json.decode(data) as Map<String, dynamic>;
}

enum Method { GET, POST, DELETE, PUT, PATCH, HEAD }
//使用:MethodValues[Method.POST]
const MethodValues = {
  Method.GET: "get",
  Method.POST: "post",
  Method.DELETE: "delete",
  Method.PUT: "put",
  Method.PATCH: "patch",
  Method.HEAD: "head",
};
网络异常处理:
import 'dart:io';

import 'package:dio/dio.dart';


class ExceptionHandle {
  static const int success = 200;
  static const int success_not_content = 204;
  static const int unauthorized = 401;
  static const int forbidden = 403;
  static const int not_found = 404;

  static const int net_error = 1000;
  static const int parse_error = 1001;
  static const int socket_error = 1002;
  static const int http_error = 1003;
  static const int timeout_error = 1004;
  static const int cancel_error = 1005;
  static const int unknown_error = 9999;

  static NetError handleException(DioError error) {
    if (error is DioError) {
      if (error.type == DioErrorType.DEFAULT ||
          error.type == DioErrorType.RESPONSE) {
        dynamic e = error.error;
        if (e is SocketException) {
          return NetError(socket_error, '网络异常,请检查你的网络!');
        }
        if (e is HttpException) {
          return NetError(http_error, '服务器异常!');
        }
        if (e is FormatException) {
          return NetError(parse_error, '数据解析错误!');
        }
        return NetError(net_error, '网络异常,请检查你的网络!');
      } else if (error.type == DioErrorType.CONNECT_TIMEOUT ||
          error.type == DioErrorType.SEND_TIMEOUT ||
          error.type == DioErrorType.RECEIVE_TIMEOUT) {
        //  连接超时 || 请求超时 || 响应超时
        return NetError(timeout_error, '连接超时!');
      } else if (error.type == DioErrorType.CANCEL) {
        return NetError(cancel_error, '取消请求');
      } else {
        return NetError(unknown_error, '未知异常');
      }
    } else {
      return NetError(unknown_error, '未知异常');
    }
  }



}

class NetError {
  int code;
  String msg;

  NetError(this.code, this.msg);
}

完成啦,有疑问的话请添加我的练习方式哦~

img

欢迎留言纠正 ~ 不妨给个点赞哈哈

我是阿T一个幽默的程序员 我们下期再见~

添加我为你的好友,领取源码以及Flutter学习资料~

在这里插入图片描述

加入我们吧,一起学习,一起进步~

在这里插入图片描述

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

编程的平行世界

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

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

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

打赏作者

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

抵扣说明:

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

余额充值