如何使API调用在头键的 Flutter 中?

ubof19bj  于 2023-05-23  发布在  Flutter
关注(0)|答案(3)|浏览(172)

假设主机站点为::
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中实现这一点?我已经搜索了几个教程,仍然在混乱中。

ctehm74n

ctehm74n1#

从dart库中导入http包,并将其别名为http,别名的原因是您不希望在文件中到处都有.get()方法建议。因此,当你使用它与http作为http.get()它会给予你的建议get,在其中你可以传递参数称为头。
代码如下:

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;
}
i86rm4rw

i86rm4rw2#

你需要把头放在http请求上。例如:

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

lnxxn5zx3#

你可以使用http flutter包,你的代码可能像这样

//Declared default headers
Map<String, String> headers = {"Accept": "application/json"};
//Passing the url
      Uri url = Uri.parse("https://dev.xyz.com/api/test");
// Make the request, make sure your function has a return type of future and add async keyword in order to use await :)
      var response = await http.post(url,headers: {...headers,'Authorization':"Bearer 7462-3172-8773-3312-5819"},body:{"email": "test@example.net",
"password": "aabbccdd",
"Name": "John",
});
      print(response.body);

在你的例子中,如果你没有使用Bearer作为你的授权关键字,你可以删除熊关键字,使用x-api-key关键字,这样示例就像

//Declared default headers
Map<String, String> headers = {"Accept": "application/json"};
//Passing the url
      Uri url = Uri.parse("https://dev.xyz.com/api/test");
// Make the request, make sure your function has a return type of future and add async keyword in order to use await :)
      var response = await http.post(url,headers: {...headers,'Authorization':"x-api-key 7462-3172-8773-3312-5819"},body:{"email": "test@example.net",
"password": "aabbccdd",
"Name": "John",
});
      print(response.body);

相关问题