【问题标题】:How to add body in Flutter http request?如何在 Flutter http 请求中添加正文?
【发布时间】:2020-08-07 15:10:37
【问题描述】:

我是新来的。我正在尝试使用 API。

我在谷歌上搜索并找到了相关代码,但我无法在 API 请求中添加表单数据。

import 'dart:convert';
import '../models/bill.dart';

Future<Stream<Bill>> getBills() async {
  final String url = 'https://api.punkapi.com/v2/beers';

  final client = new http.Client();
  final streamedRest = await client.send(http.Request('post', Uri.parse(url)));
  return streamedRest.stream
      .transform(utf8.decoder)
      .transform(json.decoder)
      .expand((data) => (data as List))
      .map((data) => Bill.fromJSON(data));
}

我必须在正文中传递'mobileno'= 1234567890。请帮帮我

【问题讨论】:

    标签: flutter flutter-http


    【解决方案1】:

    检查这个例子

        Future<Album> createAlbum(String title) async {
      final http.Response response = await http.post(
        'https://jsonplaceholder.typicode.com/albums',
        headers: <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
          'title': title,
        }),
      );
      if (response.statusCode == 201) {
        // If the server did return a 201 CREATED response,
        // then parse the JSON.
        return Album.fromJson(json.decode(response.body));
      } else {
        // If the server did not return a 201 CREATED response,
        // then throw an exception.
        throw Exception('Failed to load album');
      }
    }
    

    在此处了解更多信息 Complete example

    你也可以使用Dio包
    A powerful Http client for Dart

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2019-03-09
      相关资源
      最近更新 更多