Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何使用头键在颤振中进行API调用?_Flutter_Dart - Fatal编程技术网

Flutter 如何使用头键在颤振中进行API调用?

Flutter 如何使用头键在颤振中进行API调用?,flutter,dart,Flutter,Dart,假设主机站点为: API头键:x-API-key:7462-3172-8773-3312-5819 要注册新用户,必须调用PUT方法:{{host}}/api/customer/ 身体是这样的: {"email": "test@example.net", "password": "aabbccdd", "Name": "John", } 现在,我如何在颤振中实现这一点?我已经搜索了好几本教程,但仍然很困惑 您需要将头放在http请求上。例如: await put(urlApi + 'updat

假设主机站点为:

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

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

现在,我如何在颤振中实现这一点?我已经搜索了好几本教程,但仍然很困惑

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

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

从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;
}
检查这个:如果有什么不清楚的地方,编辑/添加到你的问题中,以显示你已经尝试了什么/你已经走了多远。