我正在开发带有Flutter的应用程序,并且在dart中使用默认的http包进行API调用。我们如何记录正在处理的所有http请求。 http或中间件中是否有内置功能可用于同一功能?
答案 0 :(得分:4)
似乎没有内置的方法来记录请求。但是,您可以实现自己的Client来记录请求:
class MyClient extends BaseClient {
MyClient(this.delegate);
final Client delegate;
Future<StreamedResponse> send(BaseRequest request) {
_logRequest(request);
return delegate.send(request);
}
void close() => delegate.close();
void _logRequest(BaseRequest request) => ....;
}
答案 1 :(得分:1)
您可以使用http_logger 像这样将它们添加到您的pubspec.yaml
http: ^0.11.3+16
http_middleware: ^1.0.0
http_logger: ^1.0.0
请注意:http_logger 1.0.0仅适用于http 0.11.3 + 16。 (更新02/04/2020)。
并将其导入到这样的文件中:
import 'package:http_middleware/http_middleware.dart';
import 'package:http_logger/http_logger.dart';
import 'package:http/http.dart' as http;
并使用它们:
HttpWithMiddleware httpClient = HttpWithMiddleware.build(middlewares: [
HttpLogger(logLevel: LogLevel.BODY),
]);
final http.Response response = await httpClient.post(
"https:nhatvm.com/v1/user/login",
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{'email': email, 'password': password}),
);
答案 2 :(得分:0)
按原样调试解决方案
class LoggableHttpClient extends BaseClient {
final Client _delegate;
final Logger _logger;
LoggableHttpClient(this._delegate, this._logger);
@override
void close() {
_delegate.close();
}
@override
Future<StreamedResponse> send(BaseRequest request) async {
String s = "${request.method} ${request.url} -->";
s += "\nheader: ${request.headers}";
if(request is Request && request.body.length>0) {
s += "\nbody: ${request.body}";
}
_logger.info(s);
final response = await _delegate.send(request);
s = "${request.method} ${request.url} <--";
s += "\nheader: ${response.headers}";
// Simple request
if(request is Request) {
final List<int> bytes = await response.stream.toBytes();
s += "\nbody: ${await utf8.decode(bytes)}";
_logger.info(s);
return StreamedResponse(
ByteStream.fromBytes(bytes),
response.statusCode,
contentLength: response.contentLength,
request: request,
headers: response.headers,
isRedirect: response.isRedirect,
persistentConnection: response.persistentConnection,
reasonPhrase: response.reasonPhrase
);
}
_logger.info(s);
return response;
}
}