1 HttpClient

HttpClient是dart自带的请求类,在io包中,实现了基本的网络请求相关的操作。

网络调用通常遵循如下步骤:

  1. 创建 client.
  2. 构造 Uri.
  3. 发起请求, 等待请求,同时您也可以配置请求headers、 body。
  4. 关闭请求, 等待响应.
  5. 解码响应的内容.

HttpClient虽然可以发送正常的网络请求,但是会暴露过多的细节:
比如需要主动关闭request请求,拿到数据后也需要手动的进行字符串解码

  1. void requestNetwork() async {
  2. // 1.创建HttpClient对象
  3. final httpClient = HttpClient();
  4. // 2.构建请求的uri
  5. final uri = Uri.parse("http://123.207.32.32:8000/api/v1/recommend");
  6. // 3.构建请求
  7. final request = await httpClient.getUrl(uri);
  8. // 4.发送请求,必须
  9. final response = await request.close();
  10. if (response.statusCode == HttpStatus.ok) {
  11. print(await response.transform(utf8.decoder).join());
  12. } else {
  13. print(response.statusCode);
  14. }
  15. }

2 http库

http 是 Dart 官方提供的另一个网络请求类,相比于 HttpClient,易用性提升了不少。
但是,没有默认集成到Dart的SDK中,所以我们需要先在pubspec中依赖它:

  1. http:^0.12.0+2
  1. import 'package:http/http.dart' as http;
  2. class _MyHomeBodyState extends State<MyHomeBody> {
  3. var msg = "";
  4. @override
  5. void initState() {
  6. print("初始化");
  7. http.get(Uri.parse("http://101.42.134.18:8080/hello")).then((response) {
  8. setState(() {
  9. msg = response.body;
  10. });
  11. });
  12. }
  13. @override
  14. Widget build(BuildContext context) {
  15. return Scaffold(
  16. body: Text("$msg"),
  17. );
  18. }
  19. }

3 dio三方库

dio是一个强大的Dart Http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载、超时、自定义适配器等…
使用dio三方库必然也需要先在pubspec中依赖它:

dio:^3.0.1

  1. import 'package:dio/dio.dart';
  2. class _MyHomeBodyState extends State<MyHomeBody> {
  3. var msg = "...";
  4. @override
  5. void initState() {
  6. print("初始化");
  7. Dio().get("http://101.42.134.18:8080/hello").then((response) {
  8. setState(() {
  9. msg = response.data.toString();
  10. });
  11. });
  12. }
  13. @override
  14. Widget build(BuildContext context) {
  15. return Scaffold(
  16. body: Text("$msg"),
  17. );
  18. }
  19. }

(1) dio库的封装

  1. import'package:dio/dio.dart';
  2. import'package:testflutter001/service/config.dart';
  3. class HTTPConfig {
  4. static const baseURL = "https://httpbin.org";
  5. static const timeout = 5000;
  6. }
  7. class HttpRequest {
  8. static final BaseOptions options = BaseOptions(
  9. baseUrl: HTTPConfig.baseURL, connectTimeout: HTTPConfig.timeout);
  10. static final Dio dio = Dio(options);
  11. static Future<T> request<T>(String url,
  12. {String method = 'get', Map<String, dynamic> params, Interceptor inter}) async {
  13. // 1.请求的单独配置
  14. final options = Options(method: method);
  15. // 2.添加第一个拦截器
  16. Interceptor dInter = InterceptorsWrapper(
  17. onRequest: (RequestOptions options) {
  18. // 1.在进行任何网络请求的时候, 可以添加一个loading显示
  19. // 2.很多页面的访问必须要求携带Token,那么就可以在这里判断是有Token
  20. // 3.对参数进行一些处理,比如序列化处理等
  21. print("拦截了请求");
  22. return options;
  23. },
  24. onResponse: (Response response) {
  25. print("拦截了响应");
  26. return response;
  27. },
  28. onError: (DioError error) {
  29. print("拦截了错误");
  30. return error;
  31. }
  32. );
  33. List<Interceptor> inters = [dInter];
  34. if (inter != null) {
  35. inters.add(inter);
  36. }
  37. dio.interceptors.addAll(inters);
  38. // 3.发送网络请求
  39. try {
  40. Response response = await dio.request<T>(url, queryParameters: params, options: options);
  41. return response.data;
  42. } on DioError catch(e) {
  43. return Future.error(e);
  44. }
  45. }
  46. }

调用

  1. HttpRequest.request("https://httpbin.org/get",
  2. params: {"name": "why", 'age': 18})
  3. .then((res) {
  4. print(res);
  5. });
  6. HttpRequest.request("https://httpbin.org/post",
  7. method: "post",
  8. params: {"name": "why", 'age': 18})
  9. .then((res) {
  10. print(res);
  11. });