Flutter 自动打印任何 http 请求 - 抽象 HTTP class

Flutter print any http request automatically - abstract HTTP class

简而言之,我想 print 在我的控制台中 print 我的应用请求的任何 Http 请求,而不是在每次调用后放置 print command 例如:

假设我有 http.Client.get 的服务,我还有另外 100 个这样的服务。

我现在正在做的是等待每项服务的响应,然后像这样打印它print('response is ' + response.body);

我想要实现的是,在我提出每个请求后,无需我写 print 100 次,它就会自动打印出来,你会推荐任何优秀的架构师吗?

希望我把这个想法搞清楚了。

您可以尝试 http_interceptor 包,它允许您从您的 http 请求中捕获所有请求和响应(更改 headers、参数等)

If you add LogInterceptor, Request and Response URLs and request body are printed. Try ...

final logInterceptor = LogInterceptor(
        requestBody: true,
        responseBody: true,
        error: false,
        requestHeader: true,
        responseHeader: true);

..interceptors.add(logInterceptor)

好吧,这是我的最后一种方法。 因为每个人都在寻求用抽象来制作它,或者说包装; 首先,如果包装 HTTP class 并在各处使用我的 class 而不是原始的 Http Class.

,我所做的是善意的

所以代码会像这样

class MHttpClient {
  final http.Client client;
  final SharedPreferences sharedPreferences;
  MHttpClient(this.client, this.sharedPreferences);

  Future<http.Response> get(
      {String path = "", Map<String, String> extraHeders}) async {
    printWrapped('get Path: $path');
    final response = await client.get(
      Uri.parse(getBaseURL() + Version + path),
      headers: getHeaders(extraHeaders: extraHeders),
    );
    printWrapped("get response : \n" + utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> post(
      {String body = "",
      String path = "",
      Map<String, String> extraHeders}) async {
    printWrapped('sended body: \n');
    printWrapped(' ${json.decode(body)}');
    final response = await client.post(
      Uri.parse(getBaseURL() + Version + path),
      body: body,
      headers: getHeaders(extraHeaders: extraHeders),
    );
    printWrapped("post response : \n" + utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> put({String body = "", String path = ""}) async {
    printWrapped('put body: \n ${json.decode(body)}');
    final response = await client.put(
      Uri.parse(getBaseURL() + Version + path),
      body: body,
      headers: getHeaders(),
    );
    printWrapped(utf8.decode(response.bodyBytes));
    return response;
  }

  Future<http.Response> putImage({File image, String path = ""}) async {
    printWrapped('Image Path: $path');
    final response = await http.put(
      Uri.parse(path),
      headers: getImageHeaders(),
      body: image.readAsBytesSync(),
    );
    return response;
  }

  String getBaseURL() {
    if (Foundation.kDebugMode)
      return BaseURLSTAGING;
    else
      return BaseURL;
  }

  String getApiKey() {
    if (Foundation.kDebugMode)
      return ApiKeyStaging;
    else
      return ApiKey;
  }

  String getToken() {
    String cashedToken = sharedPreferences.getString(CACHED_TOKEN);
    if (cashedToken == null) cashedToken = "";
    return cashedToken;
  }

  Map<String, String> getHeaders({Map extraHeaders}) {
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'x-api-key': getApiKey(),
      HttpHeaders.authorizationHeader: 'Bearer ' + getToken(),
    };
    if (extraHeaders == null || extraHeaders.isEmpty)
      return headers;
    else {
      headers.addAll(extraHeaders);
      return headers;
    }
  }

  Map<String, String> getImageHeaders() {
    return <String, String>{'Content-Type': 'image/png'};
  }

  void printWrapped(String text) {
    final pattern = RegExp('.{400}'); // 800 is the size of each chunk
    pattern.allMatches(text).forEach((match) => developer.log(match.group(0)));
  }
}

然后我在

其他地方使用了 MHttpClient
final MHttpClient client;
final response = await client.get(path: path);

在这种情况下,我不必担心其他任何事情, 当你需要改变一件事时,你只需在一个地方改变它,每件事都会保持不变并按照你想要的方式工作,而无需制动改变你必须为你所要求的一切做。