【问题标题】:How to make API call in flutter with header key?如何使用标头键进行 API 调用?
【发布时间】:2020-05-03 11:15:25
【问题描述】:

假设宿主站点是::

https://dev.xyz.com

API 标头键:“x-api-key: 7462-3172-8773-3312-5819” 要注册新用户,您必须调用 PUT 方法:{{host}}/api/customer/ 而身体是这样的:

{"email": "test@example.net",
"password": "aabbccdd",
"Name": "John",
}

现在我如何在颤振中完成这个?我已经搜索了几个教程,但仍然感到困惑。

【问题讨论】:

标签: flutter dart


【解决方案1】:

您需要将标头放在 http 请求上。例如:

await put(urlApi + 'update/'+ customer.id, headers: {'token': token, 'content-type': 'application/json'},body: body);

【讨论】:

    【解决方案2】:

    从 dart 库中导入 http 包并将其别名为 http,这种别名的原因是您不想在文件中的任何地方都有 .get() 方法建议。因此,当您将它与 http 作为http.get() 一起使用时,它会为您提供get 的建议,您可以在其中传递名为 headers 的参数。

    代码如下:

      import 'package:http/http.dart' as http;
    
      url = 'YOUR_URL';
      var response = await http.get(
        url,
        headers: {HttpHeaders.authorizationHeader: TOKEN}, //an example header
      );
    

    在你的情况下,

    import 'dart:convert';
    import 'dart:io';
    import 'dart:async';
    
    main() async {
      String url =
          'https://dev.xyz.com';
      Map map = {
        'data': {'apikey': '7462-3172-8773-3312-5819'},
      };
    
      print(await apiRequest(url, map));
    }
    
    Future<String> apiRequest(String url, Map jsonMap) async {
      HttpClient httpClient = new HttpClient();
      HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
      request.headers.set('content-type', 'application/json');
      request.add(utf8.encode(json.encode(jsonMap)));
      HttpClientResponse response = await request.close();
      // todo - you should check the response.statusCode
      String reply = await response.transform(utf8.decoder).join();
      httpClient.close();
      return reply;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 2015-11-30
      • 2013-01-01
      相关资源
      最近更新 更多