【问题标题】:flutter http request/response details including headers?颤振http请求/响应详细信息,包括标头?
【发布时间】:2020-10-22 11:16:09
【问题描述】:

虽然http 请求详细信息可以在浏览器开发工具(用于网络应用程序)中轻松检查,但我尝试探索,在那里我可以找到在 Flutter 应用程序中发送的请求的相同内容,但找不到。

例如 - 我可以通过 print(response) 看到来自 api 的实际响应,但我说的是完整的请求响应,包括 headers。

我正在为 Flutter 使用 VScode IDE。

更新:

我想查看像response.header 这样发送的标头。相同的原因就像我正在使用flutter cahe manager 而我面临的问题就像我设置了 -cache control max-age=1。

所以颤振应该在我每次访问页面时尝试获取相同的内容,它正在执行此操作,但它正在从缓存中提供页面,然后获取请求。所以如果服务器端有任何变化,它不会在第一次打开页面时反映,而是在每第二次访问时显示变化。

所以我想要的是,如果颤振从服务器获得304 response,它将从缓存中提供服务,否则它应该从获取的数据中提供服务。但它没有发生。

response.header 也没有像 200 或 304 那样显示响应代码,因此 Flutter 可以从缓存中获取或提供服务。

实际使用的代码是这样的:

Future<MyUserProfile> fetchMyUserProfile() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  final userid = prefs.getString('user_id');
  var userProfile =  await DefaultCacheManager().getSingleFile("url");        
  final response = await userProfile.readAsString();



 if (response != '') {
    print(userProfile);
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return MyUserProfile.fromJson(json.decode(response));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load Profile');
  }

}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    不想粗鲁,但您要查找的信息很容易找到...也就是说,如果您在正确的地方查找,例如官方文档。

    https://api.flutter.dev/flutter/dart-io/HttpResponse-class.html

    HttpResponse 类 ... headers → HttpHeaders 返回响应 标题。 [...] 只读

    http.Response response = await http.get(url...
    print(response.headers);
    

    编辑:回答添加到原始问题的子问题。

    要检查状态代码是什么,您只需通过response.statusCode 访问它

    例子:

      http.Response response = await http.get(url...
      if (response.statusCode == 200) {
        // do something
      } else if (response.statusCode == 304) {
        // do something else
      } else {
        // handle this
      }
    

    【讨论】:

    • 非常感谢。以及如何获取请求标头?你能帮我解决这个问题吗?
    • 您的意思是如何将标头附加到您的请求中? Cookbook,例如:http.Response response = await http.post(yourUrl,headers:{'Content-Type': 'application/json; charset=UTF-8',},body: jsonEncode({'something': someValue,})).timeout(Duration(seconds: 5));
    • 更新了我的答案。
    • 很抱歉再次打扰您,但我无法使用response.statusCode,请参阅我的更新。知道如何解决这个问题吗?
    • 是否可以从http响应中获取content-disposition: ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2020-07-08
    • 2010-10-13
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    相关资源
    最近更新 更多