Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 function to it but shouldn't it there be an easy way that is build-in but I couldn't find it in the documentation.

like image 868
Potato Avatar asked Jan 23 '19 06:01

Potato


People also ask

How do you secure HTTP request in flutter?

Open the AndroidManifest. xml file in the android/app/src/main folder. Then set usesCleartextTraffic to true .


3 Answers

This can be easily made with the Dio package.

https://pub.dartlang.org/packages/dio

Update

Based on the new Dio API:

var dio = Dio();
dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
  var customHeaders = {
    'content-type': 'application/json'
    // other headers
  };
  options.headers.addAll(customHeaders);
  return options;
}));

Response response = await dio.get("url");
print(response.data.toString());

Refer the documentation for more details.

like image 187
Martyns Avatar answered Oct 19 '22 07:10

Martyns


import 'package:http/http.dart' as http;

class MyClient extends http.BaseClient{
  http.Client _httpClient = new http.Client();

  MyClient(Map defaultHeaders);

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) {
    request.headers.addAll(defaultHeaders);
    return _httpClient.send(request);
  }
}
like image 40
Radek Manasek Avatar answered Oct 19 '22 07:10

Radek Manasek


Register custom HttpClientFactory

Dart allows to register a factory for creating an HttpClient

class MyHttpOverrides extends HttpOverrides {
  @override
  HttpClient createHttpClient(SecurityContext context) {
    return new MyHttpClient(super.createHttpClient(context));
  }
}

void main() {
  HttpOverrides.global = new MyHttpOverrides();
  runApp(MyApp());
}

Implement custom HttpClient

Implementing such a custom HttpClient seems overly complicated, but perhaps there is a better way.

The class implements HttpClient from dart:io and all its abstract classes.

The methods get(...) and getUrl(...) are customized to add a custom header using _updateHeaders(...). You would need to extend that to all other methods like head, headUrl, open, post, ...

import 'dart:io';

class MyHttpClient implements HttpClient {
  HttpClient _realClient;

  MyHttpClient(this._realClient);

  @override
  bool get autoUncompress => _realClient.autoUncompress;

  @override
  set autoUncompress(bool value) => _realClient.autoUncompress = value;

  @override
  Duration get connectionTimeout => _realClient.connectionTimeout;

  @override
  set connectionTimeout(Duration value) =>
      _realClient.connectionTimeout = value;

  @override
  Duration get idleTimeout => _realClient.idleTimeout;

  @override
  set idleTimeout(Duration value) => _realClient.idleTimeout = value;

  @override
  int get maxConnectionsPerHost => _realClient.maxConnectionsPerHost;

  @override
  set maxConnectionsPerHost(int value) =>
      _realClient.maxConnectionsPerHost = value;

  @override
  String get userAgent => _realClient.userAgent;

  @override
  set userAgent(String value) => _realClient.userAgent = value;

  @override
  void addCredentials(
          Uri url, String realm, HttpClientCredentials credentials) =>
      _realClient.addCredentials(url, realm, credentials);

  @override
  void addProxyCredentials(String host, int port, String realm,
          HttpClientCredentials credentials) =>
      _realClient.addProxyCredentials(host, port, realm, credentials);

  @override
  void set authenticate(
          Future<bool> Function(Uri url, String scheme, String realm) f) =>
      _realClient.authenticate = f;

  @override
  void set authenticateProxy(
          Future<bool> Function(
                  String host, int port, String scheme, String realm)
              f) =>
      _realClient.authenticateProxy = f;

  @override
  void set badCertificateCallback(
          bool Function(X509Certificate cert, String host, int port)
              callback) =>
      _realClient.badCertificateCallback = callback;

  @override
  void close({bool force = false}) => _realClient.close(force: force);

  @override
  Future<HttpClientRequest> delete(String host, int port, String path) =>
      _realClient.delete(host, port, path);

  @override
  Future<HttpClientRequest> deleteUrl(Uri url) => _realClient.deleteUrl(url);

  @override
  void set findProxy(String Function(Uri url) f) => _realClient.findProxy = f;

  @override
  Future<HttpClientRequest> get(String host, int port, String path) =>
      _updateHeaders(_realClient.get(host, port, path));

  Future<HttpClientRequest> _updateHeaders(
      Future<HttpClientRequest> httpClientRequest) async {
    return (await httpClientRequest)..headers.add('foo', 'bar');
  }

  @override
  Future<HttpClientRequest> getUrl(Uri url) =>
      _updateHeaders(_realClient.getUrl(url.replace(path: url.path)));

  @override
  Future<HttpClientRequest> head(String host, int port, String path) =>
      _realClient.head(host, port, path);

  @override
  Future<HttpClientRequest> headUrl(Uri url) => _realClient.headUrl(url);

  @override
  Future<HttpClientRequest> open(
          String method, String host, int port, String path) =>
      _realClient.open(method, host, port, path);

  @override
  Future<HttpClientRequest> openUrl(String method, Uri url) =>
      _realClient.openUrl(method, url);

  @override
  Future<HttpClientRequest> patch(String host, int port, String path) =>
      _realClient.patch(host, port, path);

  @override
  Future<HttpClientRequest> patchUrl(Uri url) => _realClient.patchUrl(url);

  @override
  Future<HttpClientRequest> post(String host, int port, String path) =>
      _realClient.post(host, port, path);

  @override
  Future<HttpClientRequest> postUrl(Uri url) => _realClient.postUrl(url);

  @override
  Future<HttpClientRequest> put(String host, int port, String path) =>
      _realClient.put(host, port, path);

  @override
  Future<HttpClientRequest> putUrl(Uri url) => _realClient.putUrl(url);
}
like image 12
Günter Zöchbauer Avatar answered Oct 19 '22 07:10

Günter Zöchbauer