Flutter 网络请求库http

 

集成http库

https://pub.dartlang.org/packages/http
添加依赖
dependencies:
  http: ^0.12.0
安装
flutter packages get
导入
import 'package:http/http.dart' as http;

常用方法

get(dynamic url, { Map<String, String> headers }) → Future<Response>
  • (必须)url:请求地址
  • (可选)headers:请求头
post(dynamic url, { Map<String, String> headers, dynamic body, Encoding encoding }) → Future<Response>
  • (必须)url:请求地址
  • (可选)headers:请求头
  • (可选)body:参数
  • (编码)Encoding:编码
    例子
http.post('https://flutter-cn.firebaseio.com/products.json',
            body: json.encode(param),encoding: Utf8Codec())
    .then((http.Response response) {
      final Map<String, dynamic> responseData = json.decode(response.body);
     //处理响应数据
     
    }).catchError((error) {
      print('$error错误');
    });

返回值都用到Dart Futures, 类似JavaScript中的promise
官方推荐使用async/await来调用网络请求

  void addProduct(Product product) async {
    Map<String, dynamic> param = {
      'title': product.title,
      'description': product.description,
      'price': product.price
    };
    try {
      final http.Response response = await http.post(
          'https://flutter-cn.firebaseio.com/products.json',
          body: json.encode(param),
          encoding: Utf8Codec());

      final Map<String, dynamic> responseData = json.decode(response.body);
      print('$responseData 数据');
      
    } catch (error) {
      print('$error错误');
    }
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值