Best way to set default header for all request in flutter http request

前端 未结 5 1616
臣服心动
臣服心动 2021-02-04 02:04

Sorry if this question so basic, but I am new to flutter and recently couldn\'t find a good way to set a default headers in the HTTP request I can extend the class or wrap a fun

5条回答
  •  梦毁少年i
    2021-02-04 03:06

    Just expanding on @Radek Manasek idea of a custom Client, I'm overriding all the methods so you don't have to write them again.

    import 'dart:convert';
    
    import 'package:http/http.dart' as http;
    import 'package:http/http.dart';
    
    class MyClient extends http.BaseClient {
      final Map _defaultHeaders;
      http.Client _httpClient = http.Client();
    
      MyClient(this._defaultHeaders);
    
      @override
      Future send(http.BaseRequest request) {
        return _httpClient.send(request);
      }
    
      @override
      Future get(url, {Map headers}) {
        return _httpClient.get(url, headers: _mergedHeaders(headers));
      }
    
      @override
      Future post(url, {Map headers, dynamic body, Encoding encoding}) {
        return _httpClient.post(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
      }
    
      @override
      Future patch(url, {Map headers, dynamic body, Encoding encoding}) {
        return _httpClient.patch(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
      }
    
      @override
      Future put(url, {Map headers, dynamic body, Encoding encoding}) {
        return _httpClient.put(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
      }
    
      @override
      Future head(url, {Map headers}) {
        return _httpClient.head(url, headers: _mergedHeaders(headers));
      }
    
      @override
      Future delete(url, {Map headers}) {
        return _httpClient.delete(url, headers: _mergedHeaders(headers));
      }
    
      Map _mergedHeaders(Map headers) =>
          {...?_defaultHeaders, ...?headers};
    }
    

提交回复
热议问题