Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Interceptors and Logging | Clean Architecture for API Apps
Practice
Projects
Quizzes & Challenges
Questionários
Challenges
/
Flutter REST API Integration

bookInterceptors and Logging

Interceptors are a powerful feature in network programming that allow you to intercept, modify, or monitor HTTP requests and responses before they reach your application logic or after they leave your app. In Flutter, interceptors are commonly used to automatically add headers (such as authentication tokens), handle errors in a unified way, and log requests and responses for debugging. By integrating interceptors, you can ensure that every request sent from your app contains the necessary headers, and you can capture important information about network activity without scattering logging code throughout your project.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
import 'dart:convert'; import 'package:http/http.dart' as http; class LoggingHttpClient extends http.BaseClient { final http.Client _inner; final Map<String, String> _defaultHeaders; LoggingHttpClient(this._inner, this._defaultHeaders); @override Future<http.StreamedResponse> send(http.BaseRequest request) async { // Add default headers request.headers.addAll(_defaultHeaders); // Log outgoing request print('Request: ${request.method} ${request.url}'); print('Headers: ${request.headers}'); if (request is http.Request && request.body.isNotEmpty) { print('Body: ${request.body}'); } final response = await _inner.send(request); // Log response response.stream.bytesToString().then((body) { print('Response status: ${response.statusCode}'); print('Response body: $body'); }); return response; } } void main() async { final client = LoggingHttpClient( http.Client(), { 'Authorization': 'Bearer your_token_here', 'Content-Type': 'application/json', }, ); // Example GET request final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); print('Final response status: ${response.statusCode}'); }

By using interceptors like the one above, you eliminate the need to manually add headers or logging statements to every network call in your app. This centralization not only reduces repetition but also makes it much easier to maintain and debug your code. If you ever need to update authentication logic or adjust logging, you only have to change it in one place, and the changes will apply to all requests automatically.

question mark

What is a key advantage of using interceptors in API networking?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 4

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

bookInterceptors and Logging

Deslize para mostrar o menu

Interceptors are a powerful feature in network programming that allow you to intercept, modify, or monitor HTTP requests and responses before they reach your application logic or after they leave your app. In Flutter, interceptors are commonly used to automatically add headers (such as authentication tokens), handle errors in a unified way, and log requests and responses for debugging. By integrating interceptors, you can ensure that every request sent from your app contains the necessary headers, and you can capture important information about network activity without scattering logging code throughout your project.

main.dart

main.dart

copy
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
import 'dart:convert'; import 'package:http/http.dart' as http; class LoggingHttpClient extends http.BaseClient { final http.Client _inner; final Map<String, String> _defaultHeaders; LoggingHttpClient(this._inner, this._defaultHeaders); @override Future<http.StreamedResponse> send(http.BaseRequest request) async { // Add default headers request.headers.addAll(_defaultHeaders); // Log outgoing request print('Request: ${request.method} ${request.url}'); print('Headers: ${request.headers}'); if (request is http.Request && request.body.isNotEmpty) { print('Body: ${request.body}'); } final response = await _inner.send(request); // Log response response.stream.bytesToString().then((body) { print('Response status: ${response.statusCode}'); print('Response body: $body'); }); return response; } } void main() async { final client = LoggingHttpClient( http.Client(), { 'Authorization': 'Bearer your_token_here', 'Content-Type': 'application/json', }, ); // Example GET request final response = await client.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); print('Final response status: ${response.statusCode}'); }

By using interceptors like the one above, you eliminate the need to manually add headers or logging statements to every network call in your app. This centralization not only reduces repetition but also makes it much easier to maintain and debug your code. If you ever need to update authentication logic or adjust logging, you only have to change it in one place, and the changes will apply to all requests automatically.

question mark

What is a key advantage of using interceptors in API networking?

Select the correct answer

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 4
some-alt