flutter httpClient的封装 dio

1.get请求

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class MyHttp extends StatefulWidget {
  @override
  State createState() {
    // TODO: implement createState
    return _MyHttp();
  }
}

class _MyHttp extends State {
  
  Dio dio = Dio();

  Response response;

  String _text = "";

  _getData() async {

    response = await dio
        .get("http://172.16.3.25:8091/mantis/systemInit/loadInitStatus");
    setState(() {
      _text = response.data.toString();
    });

    // 传参数
    response = await dio.get(
        "http://172.16.3.25:8092/mantis-auth/api/coreresource/i18n/getLangItems/v1",
        queryParameters: {"languageCode": "zh_CN"});

    print(response.data.toString());
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("http"),
      ),
      body: Column(
        children: [
          Row(
            children: [
              RaisedButton(
                child: Text("获取信息"),
                onPressed: () {
                  _getData();
                },
              )
            ],
          ),
          Text(_text)
        ],
      ),
    );
  }
}
Response({
  this.data, //数据
  this.headers, //头部
  this.request,  //请求
  this.redirects,
  this.statusCode ,  //状态码
  this.statusMessage,  //状态信息
  this.extra,
});

flutter httpClient的封装 dio_第1张图片

2. post请求

response = await dio.post("/test", data: {"id": 12, "name": "wendu"});

3.FormData post

FormData formData = new FormData.from({
    "name": "wendux",
    "age": 25,
  });

response = await dio.post("/info", data: formData);

4.downLoad 下载

import 'dart:io';

import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class MyHttp extends StatefulWidget {
  @override
  State createState() {
    // TODO: implement createState
    return _MyHttp();
  }
}

class _MyHttp extends State {

  Dio dio = Dio();

  Response response;

  _downLoad() async {
    // 路径
    Directory d = await getExternalStorageDirectory();
    // 外部存储目录:可以使用getExternalStorageDirectory()来获取外部存储目录,如SD卡;
    // 由于iOS不支持外部目录,所以在iOS下调用该方法会抛出UnsupportedError异常,
    // 而在Android下结果是android SDK中getExternalStorageDirectory的返回值

    response = await dio.download(
        "https://ss0.baidu.com/73t1bjeh1BF3odCf/it/u=4098380510,1804686846&fm=85&s=2341326EE8E7240541B76D020300C09B",
        d.path + "/test.jpg", onReceiveProgress: (int count, int total) {
      //进度
      print("$count ---- $total");
    });
    print('downloadFile success');
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("http"),
      ),
      body: Column(
        children: [
          Row(
            children: [
              RaisedButton(
                child: Text("下载"),
                onPressed: () {
                  _downLoad();
                },
              ),
            ],
          )
        ],
      ),
    );
  }
}

flutter httpClient的封装 dio_第2张图片  flutter httpClient的封装 dio_第3张图片

5. Upload 上传

class UploadFileInfo {
  UploadFileInfo(this.file, this.fileName, {ContentType contentType})
      : bytes = null,
        this.contentType = contentType ?? ContentType.binary;

  UploadFileInfo.fromBytes(this.bytes, this.fileName, {ContentType contentType})
      : file = null,
        this.contentType = contentType ?? ContentType.binary;

  /// The file to upload.
  final File file;

  /// The file content
  final List bytes;

  /// The file name which the server will receive.
  final String fileName;

  /// The content-type of the upload file. Default value is `ContentType.binary`
  ContentType contentType;
}
_upload() async {
    Directory d = await getExternalStorageDirectory();
    FormData fm = new FormData.from({
      "languageCode": "zh_cn",
      "excelFile": UploadFileInfo(File(d.path + "/test.jpg"), "upload.jpg")
    });
    response = await dio.post(
        "http://172.16.1.124:8091/mantis/destination/uploadDestination",
        data: fm,
        // 上传进度
        onSendProgress: (int sent, int total) {
             print("$sent $total");
        },
    );
    print(response.data);
}

 6.Dio的基础设置

Dio dio = new Dio();

// 设置options
dio.options.baseUrl = "https://www.xx.com/api";
dio.options.connectTimeout = 5000; //5s
dio.options.receiveTimeout = 3000;




// BaseOptions传参

Options options = new BaseOptions(
    baseUrl: "https://www.xx.com/api",
    connectTimeout: 5000,
    receiveTimeout: 3000,
);
Dio dio = new Dio(options);

Options: 

{
  /// 方法
  String method;

  /// 基础路由
  String baseUrl;

  /// headers.
  Map headers;

   /// 打开url的连接时间 毫秒
  int connectTimeout;

   ///  Whenever more than [receiveTimeout] (in milliseconds) passes between two events from response stream,
  ///  [Dio] will throw the [DioError] with [DioErrorType.RECEIVE_TIMEOUT].
  ///  Note: This is not the receiving time limitation.
  int receiveTimeout;

  /// 数据
  T data;

  /// 路径
  /// 如果http(s)开头, baseURL就忽略,
  /// 否则将连在baseURL后面
  String path="";

  /// The request Content-Type. The default value is [ContentType.JSON].
  /// If you want to encode request body with "application/x-www-form-urlencoded",
  /// you can set `ContentType.parse("application/x-www-form-urlencoded")`, and [Dio]
  /// will automatically encode the request body.
  ContentType contentType;

  /// [responseType] indicates the type of data that the server will respond with
  /// options which defined in [ResponseType] are `JSON`, `STREAM`, `PLAIN`.
  ///
  /// The default value is `JSON`, dio will parse response string to json object automatically
  /// when the content-type of response is "application/json".
  ///
  /// If you want to receive response data with binary bytes, for example,
  /// downloading a image, use `STREAM`.
  ///
  /// If you want to receive the response data with String, use `PLAIN`.
  ResponseType responseType;
  
  /// `validateStatus` defines whether the request is successful for a given
  /// HTTP response status code. If `validateStatus` returns `true` ,
  /// the request will be perceived as successful; otherwise, considered as failed.
  ValidateStatus validateStatus;

  /// Custom field that you can retrieve it later in [Interceptor]、[Transformer] and the   [Response] object.
  Map extra;
  
  /// Custom Cookies
  Iterable cookies;
}
Response responseMap = await dio.get(
    "/test",
    // Transform response data to Json Map
    options: new Options(responseType: ResponseType.json),
);

print(responseMap.data);

response = await dio.post(
    "/test",
    data: {
      "id": 8,
      "info": {"name": "wendux", "age": 25}
    },
    // Send data with "application/x-www-form-urlencoded" format
    options: new Options(
        contentType: ContentType.parse("application/x-www-form-urlencoded")),
  );
  print(response.data);
}

7.Dio的拦截器

dio.interceptors.add(InterceptorsWrapper(
    //请求
    onRequest:(RequestOptions options){
     // Do something before request is sent
     return options; //continue
     // If you want to resolve the request with some custom data,
     // you can return a `Response` object or return `dio.resolve(data)`.
     // If you want to reject the request with a error message, 
     // you can return a `DioError` object or return `dio.reject(errMsg)`    
    },
    //响应
    onResponse:(Response response) {
     // Do something with response data
     return response; // continue
    },
    //报错
    onError: (DioError e) {
     // Do something with response error
     return  e;//continue
    }
));
//内部有Async

dio.interceptors.add(InterceptorsWrapper(
    onRequest:(Options options) async{
        //...If no token, request token firstly.
        Response response = await dio.get("/token");
        //Set the token to headers 
        options.headers["token"] = response.data["data"]["token"];
        return options; //continue   
    }
));
lock/unlock 一旦请求/响应拦截器被锁定,接下来的请求/响应将会在进入请求/响应拦截器之前排队等待,直到解锁后,这些入队的请求才会继续执行(进入拦截器)

lock之后如果没有unlock,就会进不到拦截器,也就不能响应

简写: resuest的
dio.lock() == dio.interceptors.requestLock.lock()
dio.unlock() == dio.interceptors.requestLock.unlock()
dio.clear() == dio.interceptors.requestLock.clear()

dio.interceptors.responseLock.lock();  //response
dio.interceptors.errorLock.lock();   // error


例子:

import 'dart:io';

import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

Dio dio = new Dio();  //定义拦截器的dio
Dio tokenDio = new Dio(); //拦截器内部请求,因为lock了,上面的dio就进不来了

class MyHttp extends StatefulWidget {
  @override
  State createState() {
    // TODO: implement createState
    return _MyHttp();
  }
}

class _MyHttp extends State {
  void initState() {
    print("in");
    super.initState();
    tokenDio.options = dio.options;
    dio.interceptors.clear();
    dio.interceptors.add(InterceptorsWrapper(onRequest: (options) async {
      dio.interceptors.requestLock.lock();
      await tokenDio.get("http://172.16.3.25:8091/mantis/systemInit/loadInitStatus");
      print("interceptors");
      dio.interceptors.requestLock.unlock();
      return options;
    }, onResponse: (Response response) {
      print("响应之前");
      // Do something with response data
      return response; // continue
    }, onError: (DioError e) {
      print("错误之前");
      // Do something with response error
      return e; //continue
    }));
  }

  Response response;

  String _text = "";

  _getData() async {
    print(2);
    response = await dio
        .get("http://172.16.3.25:8091/mantis/systemInit/loadInitStatus");
    print(response);
    setState(() {
      _text = response.data.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text("http"),
      ),
      body: Column(
        children: [
          Row(
            children: [
              RaisedButton(
                child: Text("获取信息"),
                onPressed: () {
                  _getData();
                },
              )
            ],
          ),
          Text(_text)
        ],
      ),
    );
  }
}

 

你可能感兴趣的:(flutter)