Flutter Http 소스 저장소-dio 요청

27572 단어
dio는 Flutter 중국어 네트워크에서 시작된 강력한 Dart Http 요청 라이브러리로 Restful API,Form Data, 차단기, 요청 취소, 쿠키 관리, 파일 업로드/다운로드, 시간 초과 등을 지원합니다.
문서 언어: English | 중국어 간체
dio
Restful API, FormData, 차단기, 취소 요청, 쿠키 관리, 파일 업로드/다운로드, 시간 초과 등을 지원하는 강력한 Dart Http 요청 라이브러리
의존성 추가
dependencies:
  dio: ^x.x.x  // latest version

아주 간단한 예
import 'package:dio/dio.dart';
Dio dio = new Dio();
Response response=await dio.get("https://www.google.com/");
print(response.data);

컨텐트 목록
  • Dio APIs
  • 요청 구성
  • 응답 데이터
  • 차단기
  • 오류 처리
  • 응용 프로그램/x-www-form-urlencoded 인코딩 사용
  • FormData
  • 변환기
  • Http 에이전트 설정
  • 취소 요청
  • 쿠키 관리
  • Features and bugs

  • 예제GET 요청을 시작합니다.
    Response response;
    response=await dio.get("/test?id=12&name=wendu")
    print(response.data.toString());
    //              ,        :
    response=await dio.get("/test",data:{"id":12,"name":"wendu"})
    print(response.data.toString());
    
    POST 요청을 시작합니다.
    response=await dio.post("/test",data:{"id":12,"name":"wendu"})
    

    여러 개의 동시 요청을 시작합니다.
    response= await Future.wait([dio.post("/info"),dio.get("/token")]);
    

    파일을 다운로드하려면 다음과 같이 하십시오.
    response=await dio.download("https://www.google.com/","./xx.html")
    

    FormData 보내기
    FormData formData = new FormData.from({
       "name": "wendux",
       "age": 25,
    });
    response = await dio.post("/info", data: formData)
    

    FormData를 통해 여러 파일을 업로드합니다.
    FormData formData = new FormData.from({
       "name": "wendux",
       "age": 25,
       "file1": new UploadFileInfo(new File("./upload.txt"), "upload1.txt")
       "file2": new UploadFileInfo(new File("./upload.txt"), "upload2.txt")
    });
    response = await dio.post("/info", data: formData)
    

    여기에서 모든 예시 코드를 얻을 수 있습니다.
    Dio APIs
    Dio 인스턴스를 생성하고 구성합니다.
    Dio 인스턴스를 생성하려면 기본 구성이나 옵션 Options 매개 변수를 전송할 수 있습니다.
    Dio dio = new Dio; //       
    
    //   dio  
    dio.options.baseUrl="https://www.xx.com/api" 
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout=3000;  
    
    //          `options`   dio  
    Options options= new Options(
        baseUrl:"https://www.xx.com/api",
        connectTimeout:5000,
        receiveTimeout:3000
    );
    Dio dio = new Dio(options);
    

    Dio 인스턴스의 핵심 API는 다음과 같습니다.
    Future request(String path, {data, Options options,CancelToken cancelToken})
    response=await request("/test", data: {"id":12,"name":"xx"}, new Options(method:"GET"));
    

    요청 방법 별칭
    사용하기 편리하도록 Dio는 다른 Restful API를 제공했는데 이 API들은 모두 request의 별명이다.
    Future get(path, {data, Options options,CancelToken cancelToken})
    Future post(path, {data, Options options,CancelToken cancelToken})
    Future put(path, {data, Options options,CancelToken cancelToken})
    Future delete(path, {data, Options options,CancelToken cancelToken})
    Future head(path, {data, Options options,CancelToken cancelToken})
    Future put(path, {data, Options options,CancelToken cancelToken})
    Future path(path, {data, Options options,CancelToken cancelToken})
    Future download(String urlPath, savePath, {OnDownloadProgress onProgress, data, bool flush: false, Options options,CancelToken cancelToken})
    구성 요청
    다음은 모든 요청 설정 옵션입니다.요청 method이 지정되지 않은 경우 기본값은 GET입니다.
    {
      /// Http method.
      String method;
    
      ///      ,       , : "https://www.google.com/api/".
      String baseUrl;
    
      /// Http   .
      Map<String, dynamic> headers;
    
      ///          ,     .
      int connectTimeout;
    
      ///                  ,     。        [receiveTimeout],
      ///  [Dio]       [DioErrorType.RECEIVE_TIMEOUT]   .
      ///    :             .
      int receiveTimeout;
    
      ///     ,       .
      var data;
    
      ///     ,   `path`   "http(s)"  ,   `baseURL`     ;   ,
      ///    baseUrl       url.
      String path="";
    
      ///    Content-Type,    [ContentType.JSON].
      ///      "application/x-www-form-urlencoded"        ,
      ///          `ContentType.parse("application/x-www-form-urlencoded")`,    [Dio]
      ///          .
      ContentType contentType;
    
      /// [responseType]          (  )      。
      ///    [ResponseType]        `JSON`, `STREAM`, `PLAIN`.
      ///
      ///      `JSON`,      content-type "application/json" ,dio            json  。
      ///                ,          ,       `STREAM`.
      ///
      ///       (   )        ,    `PLAIN`.
      ResponseType responseType;
    
      ///        ,    [Interceptor]、[TransFormer]   [Response]    .
      Map<String, dynamic> extra;
    }
    

    여기에 완성된 예가 하나 있다.
    응답 데이터
    요청이 성공하면 다음과 같은 필드가 포함된 Response 객체가 반환됩니다.
    {
      ///     ,          ,      Options  [ResponseType].
      var data;
      ///    
      HttpHeaders headers;
      ///       
      Options request;
      /// Http status code.
      int statusCode;
      ///           (          ),      `then`   .
      Map<String, dynamic> extra;
    }
    

    예는 다음과 같습니다.
    Response response=await dio.get("https://www.google.com");
    print(response.data);
    print(response.headers);
    print(response.request);
    print(statusCode);
    

    차단기
    모든 디오 실례에는 요청 차단기 RequestInterceptor과 응답 차단기 ResponseInterceptor이 있습니다. 차단기를 통해 요청하기 전이나 응답 후(하지만 아직 then 또는 catchError 처리되지 않았음)에서 통일된 예처리 작업을 할 수 있습니다.
     dio.interceptor.request.onSend = (Options options){
         //              
         return options; //continue
         //                   ,      `Response`     `dio.resolve(data)`。
         //          ,  then    ,then               data.
         //
         //                ,       `DioError`  ,   `dio.reject(errMsg)`,
         //              ,  catchError    。   
     }
     dio.interceptor.response.onSuccess = (Response response) {
         //                
         return response; // continue
     };
     dio.interceptor.response.onError = (DioError e){
         //             
         return DioError;//continue
     }    
    

    차단기를 제거하려면null:
    dio.interceptor.request.onSend=null;
    dio.interceptor.response.onSuccess=null;
    dio.interceptor.response.onError=null;
    

    요청/응답 완료 및 종료
    모든 차단기에서 요청 실행 흐름을 변경할 수 있습니다. 요청/응답을 완성하고 사용자 정의 데이터를 되돌려주고 싶으면 Response 대상을 되돌려주거나 dio.resolve(data)의 결과를 되돌려줍니다.만약 당신이 요청/응답을 중지하고 싶다면, catchError의 대상을 되돌려주거나 DioError의 결과를 되돌려줄 수 있습니다.
     dio.interceptor.request.onSend = (Options options){
         return dio.resolve("fake data")    
     }
     Response response= await dio.get("/test");
     print(response.data);//"fake data"
    

    차단기에서 비동기 작업 지원
    다음 예제에서는 동기화 작업뿐만 아니라 비동기 작업도 지원합니다.
      dio.interceptor.request.onSend = (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 차단기
    차단기의 dio.reject(errMsg)/lock() 방법을 사용해서 차단기를 잠그거나 잠글 수 있습니다.요청/응답 차단기가 잠기면 다음 요청/응답은 요청/응답 차단기에 들어가기 전에 줄을 서서 잠금이 해제될 때까지 기다립니다(차단기에 들어가기).이것은 직렬화 요청/응답이 필요한 장면에서 매우 실용적이다. 다음에 우리는 예시를 하나 제시할 것이다.
    tokenDio=new Dio(); //Create a new instance to request the token.
    tokenDio.options=dio;
    dio.interceptor.request.onSend = (Options options) async{
         // If no token, request token firstly and lock this interceptor
         // to prevent other request enter this interceptor.
         dio.interceptor.request.lock(); 
         // We use a new Dio(to avoid dead lock) instance to request token. 
         Response response = await tokenDio.get("/token");
         //Set the token to headers 
         options.headers["token"] = response.data["data"]["token"];
         dio.interceptor.request.unlock() 
         return options; //continue   
     }
    

    별명
    요청 차단기가 잠겼을 때 다음 요청은 중단됩니다. 이것은 dio 실례를 잠근 것과 같습니다. 따라서 Dio 예시에서 요청 차단기 unlock의 별명 방법을 제공합니다.
    dio.lock() == dio.interceptor.request.lock()
    dio.unlock() == dio.interceptor.request.unlock()
    예제
    만약에 이런 장면을 가정하면 안전한 이유로 우리는 모든 요청 헤더에 csrfToken을 추가해야 한다. 만약에 csrfToken이 존재하지 않는다면 우리는 먼저 csrfToken을 요청하고 csrfToken을 얻은 다음에 후속 요청을 한다.csrfToken을 요청하는 과정은 비동기적이기 때문에 우리는 요청 과정에서 후속 요청(csrfToken이 필요하기 때문)을 잠그고 csrfToken 요청이 성공할 때까지 잠금을 해제해야 한다. 코드는 다음과 같다.
    dio.interceptor.request.onSend = (Options options) {
        print('send request:path:${options.path},baseURL:${options.baseUrl}');
        if (csrfToken == null) {
          print("no token,request token firstly...");
          //lock the dio.
          dio.lock();
          return tokenDio.get("/token").then((d) {
            options.headers["csrfToken"] = csrfToken = d.data['data']['token'];
            print("request token succeed, value: " + d.data['data']['token']);
            print('continue to perform request:path:${options.path},baseURL:${options.path}');
            return options;
          }).whenComplete(() => dio.unlock()); // unlock the dio
        } else {
          options.headers["csrfToken"] = csrfToken;
          return options;
        }
      };
    

    온전한 예시 코드는 여기를 클릭하세요.
    오류 처리
    요청 시 오류가 발생하면 Dio는 lock/unlockError/Exception으로 포장합니다.
      try {
        //404  
        await dio.get("https://wendux.github.io/xsddddd");
       } on DioError catch(e) {
          // The request was made and the server responded with a status code
          // that falls out of the range of 2xx and is also not 304.
          if(e.response) {
            print(e.response.data) 
            print(e.response.headers) 
            print(e.response.request)    
          } else{
            // Something happened in setting up or sending the request that triggered an Error  
            print(e.request)  
            print(e.message)
          }  
      }
    

    DioError 필드
     {
      ///     ,                  ,   `null`
      Response response;
    
      ///     .
      String message;
      
      ///     ,   
      DioErrorType type;
    
      ///      ,   null
      StackTrace stackTrace;
    }
    

    DioErrorType
    enum DioErrorType {
      /// Default error type, usually occurs before connecting the server.
      DEFAULT,
    
      /// When opening  url timeout, it occurs.
      CONNECT_TIMEOUT,
    
      ///  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.
      RECEIVE_TIMEOUT,
    
      /// When the server response, but with a incorrect status, such as 404, 503...
      RESPONSE,
    
      /// When the request is cancelled, dio will throw a error with this type.
      CANCEL
    }
    

    응용 프로그램/x-www-form-urlencoded 인코딩 사용
    기본적으로 Dio는 요청 데이터(String 유형 제외)를 DioError으로 서열화합니다.JSON 형식으로 인코딩하려면 application/x-www-form-urlencoded을 명시적으로 설정할 수 있습니다.
    //Instance level
    dio.options.contentType=ContentType.parse("application/x-www-form-urlencoded");
    //or works once
    dio.post("/info",data:{"id":5}, options: new Options(contentType:ContentType.parse("application/x-www-form-urlencoded")))    
    

    여기에 예시가 하나 있다.
    FormData
    Dio는 FormData 발송을 지원하며 요청 데이터는 contentType으로 인코딩되며 FormData에 파일이 하나 이상 포함될 수 있습니다.
    FormData formData = new FormData.from({
        "name": "wendux",
        "age": 25,
        "file": new UploadFileInfo(new File("./example/upload.txt"), "upload.txt")
    });
    response = await dio.post("/info", data: formData)
    

    참고: FormData 전송은 post 방법에서만 지원됩니다.
    여기에 완전한 예가 하나 있다.
    컨버터
    변환기 multipart/form-data은 요청 데이터와 응답 데이터를 코딩 처리하는 데 사용됩니다.Dio는 기본 변환기 TransFormer을 기본 DefaultTransformer으로 구현했습니다.요청/응답 데이터에 대한 사용자 정의 코딩 처리를 원한다면 TransFormer 설정을 통해 사용자 정의 변환기를 제공할 수 있습니다.
    요청 변환기 dio.transformer은'PUT','POST','PATCH'방법에만 사용됩니다. 이 방법들만 요청체(request body)를 휴대할 수 있기 때문입니다.그러나 응답 변환기 TransFormer.transformRequest(...)은 모든 요청 방법의 반환 데이터에 사용됩니다.
    실행 흐름
    차단기에서도 데이터를 미리 처리할 수 있지만 변환기의 주요 직책은 요청/응답 데이터를 인코딩하는 것이다. 전환기를 단독으로 분리하는 이유는 첫째, 차단기와 결합을 풀기 위해서이다. 둘째, 원시 요청 데이터를 수정하지 않기 위해서이다. (만약 차단기에서 요청 데이터(options.data)를 수정하면 원시 요청 데이터를 덮어쓰고 일부 경우 원시 요청 데이터가 필요할 수도 있다).Dio의 요청 흐름은 다음과 같습니다.
    요청 차단기 > 요청 변환기 > 시작 요청 > 응답 변환기 > 응답 차단기 >> 최종 결과입니다.
    이것은 사용자 정의 변환기의 예이다.
    Http 프록시 설정
    Dio는 HttpClient에서 요청한 http 요청이므로 다음과 같이 TransFormer.transformResponse()을 구성하여 에이전트를 지원할 수 있습니다.
      dio.onHttpClientCreate = (HttpClient client) {
        client.findProxy = (uri) {
          //proxy all request to localhost:8888
          return "PROXY localhost:8888";
        };
      };
    

    온전한 예는 이곳을 보십시오.
    취소 요청
    cancel token을 통해 요청을 취소할 수 있습니다.
    CancelToken token = new CancelToken();
    dio.get(url, cancelToken: token)
        .catchError((DioError err){
            if (CancelToken.isCancel(err)) {
                print('Request canceled! '+ err.message)
            }else{
                // handle error.
            }
        })
    // cancel the requests with "cancelled" message.
    token.cancel("cancelled");
    

    주의: 같은 cancel token은 여러 요청에 사용할 수 있습니다. 한 cancel token이 취소되면 이 cancel token을 사용하는 모든 요청이 취소됩니다.
    완전한 예시는 예시를 취소하는 것을 참고하십시오.
    쿠키 관리
    당신은 httpClient을 통해 요청/응답 cooki를 자동으로 관리할 수 있습니다.
    dio cookie 관리 API는 오픈 소스 라이브러리 기반 cookiejar. cookieJar 또는 CookieJar을 만들어서 쿠키를 자동으로 관리할 수 있습니다. dio는 기본적으로 PersistCookieJar을 사용합니다. 쿠키를 메모리에 저장합니다.쿠키를 영구화하려면 CookieJar을 사용하십시오. 예제 코드는 다음과 같습니다.
    var dio = new Dio();
    dio.cookieJar=new PersistCookieJar("./cookies");
    
    PersistCookieJar은 RFC의 표준 쿠키 정책을 구현합니다.PersistCookieJar은 쿠키를 파일에 저장하기 때문에 쿠키는 PersistCookieJar이 삭제되지 않는 한 계속 존재합니다.
    쿠키에 대한 자세한 내용jar 참조:github.com/flutterchin… .
    Copyright & License
    이 소스 오픈 프로젝트는 Flutter 중국어 네트워크(flutterchina.club)에 의해 권한을 부여받았고 license는 MIT입니다.마음에 드시면 스타를 환영합니다.
    Flutter 중국어 네트워크 오픈 소스 프로젝트 계획
    Flutter SDK 외에 자주 사용하는(실용적인) Package, 플러그인을 개발하여 Flutter 제3자 라이브러리를 풍부하게 하고 Flutter 생태에 중국 개발자의 힘을 기여한다.모든 프로젝트는 Github Flutter 중국어 사이트 Organization에 발표되고 모든 원본 공헌자는 저희 Organization에 가입하여 멤버가 됩니다.현재 지역사회에 이미 몇 개의 개원 프로젝트가 공개 테스트를 시작했습니다. 개발이나 테스트에 가입하신 것을 환영합니다. 자세한 내용은 Flutter 중국어 네트워크 개원 프로젝트를 보십시오."소스 오픈 프로젝트 계획"에 가입하려면[email protected]자기소개(개인기본정보+특기/관심 기술)를 첨부합니다.
    Features and bugs
    Please file feature requests and bugs at the issue tracker.

    좋은 웹페이지 즐겨찾기