我创建了一个 API,可以通过 GET 请求根据给定的 id
从数据库读取数据。
它获取一些数据,其中 id
等于某个整数。
我想使用 package:http/http.dart
在 Flutter 中调用此 API,但 GET 请求不允许我输入请求正文(我将在其中传递 id
)。
我在谷歌上搜索了又谷歌,但没有结果(我可能只是搜索错了东西)。我尝试将 API 更改为 POST 而不是 GET,这可行,但我觉得它违背了 GET 的目的。
这是我使用 POST 的方法:
String url = "http://example.com/api/v1";
Map<String, String> headers = {"Content-type": "application/json"};
String json = '{"id": 1}';
Response response = await post(url, headers: headers, body: json);
但是我可以在 Flutter 中使用 GET 来实现这一点吗?
最佳答案
您可以使用Request
class为此:
final request = Request('GET', 'http://example.com/api/v1');
request.body = '{"id": 1}';
final response = request.send().stream.first;
或者,您也可以使用惯用语法,即标准过程,并在 URI 中提供您的参数:
await get('http://example.com/api/v1?id=1', headers: headers, body: json);
关于flutter - Flutter 中是否可以使用 body 发出 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57699916/