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
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());
}
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);
}
this simple and easy way worked for me
var _dio = Dio();
_dio.options.headers= {"Authorization" : token};
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.
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);
}
}
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<String, String> _defaultHeaders;
http.Client _httpClient = http.Client();
MyClient(this._defaultHeaders);
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
return _httpClient.send(request);
}
@override
Future<Response> get(url, {Map<String, String> headers}) {
return _httpClient.get(url, headers: _mergedHeaders(headers));
}
@override
Future<Response> post(url, {Map<String, String> headers, dynamic body, Encoding encoding}) {
return _httpClient.post(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future<Response> patch(url, {Map<String, String> headers, dynamic body, Encoding encoding}) {
return _httpClient.patch(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future<Response> put(url, {Map<String, String> headers, dynamic body, Encoding encoding}) {
return _httpClient.put(url, headers: _mergedHeaders(headers), body: body, encoding: encoding);
}
@override
Future<Response> head(url, {Map<String, String> headers}) {
return _httpClient.head(url, headers: _mergedHeaders(headers));
}
@override
Future<Response> delete(url, {Map<String, String> headers}) {
return _httpClient.delete(url, headers: _mergedHeaders(headers));
}
Map<String, String> _mergedHeaders(Map<String, String> headers) =>
{...?_defaultHeaders, ...?headers};
}