【问题标题】:How can I add multiple headers in Flutter GET Api request如何在 Flutter GET Api 请求中添加多个标头
【发布时间】:2019-07-16 06:57:45
【问题描述】:

如何在 Flutter API 的标头中添加 set-cookie。我使用了以下 dart 插件:

Dart Plugin

我正在关注这些链接,但无法添加标题。

Flutter Cookbook

Stackoverflow Question

以下是我的代码:

Future<Map> getApi() async {

    Map<String, String> headers = {};

    // HEADERS TO BE ADDED
    headers['Set-Cookie'] = "user_image=; Path=/";
    headers['Set-Cookie'] = "user_id=Administrator; Path=/";
    headers['Set-Cookie'] = "system_user=yes; Path=/";
    headers['Set-Cookie'] = "full_name=Administrator; Path=/";
    headers['Set-Cookie'] = "sid=123456789; Expires=Mon, 25-Feb-2019 11:01:39 GMT; Path=/";

    // API RESPONSE
    http.Response response = await http.get(
      apiUrl,
      headers: headers,
    );

    // CONVERT TO JSON AND MAP
    Map responseBody = convert.jsonDecode(response.body);

    return responseBody;
  }

【问题讨论】:

    标签: http cookies dart flutter http-headers


    【解决方案1】:

    这应该做你想做的事

      HttpClient client = HttpClient();
      final request = await client.getUrl(Uri.parse("http://www.example.com/"));
      request.cookies
        ..add((Cookie('user_image', '')..path = '/'))
        ..add((Cookie('user_id', 'Administrator')..path = '/'))
        ..add((Cookie('system_user', 'yes')..path = '/'))
        ..add((Cookie('full_name', 'Administrator')..path = '/'))
        ..add((Cookie('sid', '123456789')..path = '/')
          ..expires = DateTime.utc(2019, 2, 25, 11, 01, 39));
      //request.write(...)
      final response = await request.close();
    

    【讨论】:

    • 未处理异常:\n错误状态:Stream 已被监听。
    【解决方案2】:

    这应该工作;

    HttpClient client = HttpClient();
        final request = await client.send(http.Request("GET", Uri.parse("http://www.example.com/"))
                ..headers['Set-Cookie'] = "user_image=; Path=/"
                ..headers['Set-Cookie'] = "user_id=Administrator; Path=/"
                ..headers['Set-Cookie'] = "system_user=yes; Path=/"
                ..headers['Set-Cookie'] = "full_name=Administrator; Path=/"
                ..headers['Set-Cookie'] = "sid=123456789; Expires=Mon, 25-Feb-2019 11:01:39 GMT; Path=/"
    

    【讨论】:

    • 错误:没有为类 HttpClient 定义“发送”方法。
    【解决方案3】:

    借助link 上给出的解决方案,我能够解决我的问题。以下是添加标头的 HTTP 请求:

    http.Response response = await http.get(
       apiUrl,
       headers: {'Cookie': 'sid=123456789'},
    );
    

    感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 2013-10-28
      • 1970-01-01
      • 2021-04-01
      • 2015-08-30
      • 2018-07-01
      相关资源
      最近更新 更多