dart-lang / http

A composable API for making HTTP requests in Dart.
https://pub.dev/packages/http
BSD 3-Clause "New" or "Revised" License
1.02k stars 354 forks source link

support for Interceptor #710

Open beamAkshay opened 2 years ago

devoncarew commented 2 years ago

Hi - can you add a few more details about your request? What the feature would look like, how it might change the API, and example from a library in another language...? Thanks!

beamAkshay commented 2 years ago

Interceptor feature like dio package has because I want to refresh token when it is expired. and I did not find any way to do that in this package. but using Interceptor we can do that easily.

devoncarew commented 2 years ago

Thanks!

For posterity, here's a link to more info: https://pub.dev/packages/dio#interceptors.

And in-lined:

... interceptors, by which we can intercept requests 、 responses and errors before they are handled by then or catchError

maRci002 commented 2 years ago

If you are familiar with Decorator pattern you can simply do your own interceptors like this:

import 'dart:async';

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

typedef GetAccessToken = Future<String?> Function();

class AuthClient extends http.BaseClient {
  AuthClient({
    required this.getAccessToken,
  });

  final _client = http.Client();
  final GetAccessToken getAccessToken;

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    if (request.headers['authorization'] == null) {
      // add authorization header if it isn't exists
      final accessToken = await getAccessToken();
      if (accessToken != null) {
        request.headers['authorization'] = 'Bearer $accessToken';
      }
    }

    return _client.send(request);
  }

  @override
  void close() {
    _client.close();

    super.close();
  }
}
coolRoger commented 7 months ago

we also need a Interceptor to log request send and response, any good approach to added a Interceptor using this library?

xpwmaosldk commented 3 months ago

How can I check the response?