Flutter 网络请求库http

包地址

https://pub.dartlang.org/packages/http

pubspec.yaml 里面

添加依赖

Code bashLine:2复制
  • 1.
  • 2.
    • dependencies:
    • http: ^0.12.0

    安装 

    vscode 会自动安装,andrio studio 需要手动点击 Pub get

    Code bashLine:1复制
  • 1.
    • flutter packages get

    导入

    Code bashLine:1复制
  • 1.
    • import 'package:http/http.dart' as http;

    使用案例

    Code bashLine:23复制
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
    • // http请求 方式1
    • httpRequest1(){
    • var url = 'https://randomuser.me/api/?results=30';
    • http.get(Uri.parse(url)).then((res){
    • print("获取到的数据:${res.body}" );
    • });
    • }
    • // http 请求 方式2 原生
    • httpRequest2() async {
    • var url = 'https://randomuser.me/api/?results=30';
    • try {
    • var response = await http.get(Uri.parse(url));
    • if (response.statusCode == 200) {
    • var jsonString = response.body;
    • print(jsonString);
    • } else {
    • print('请求失败状态为: ${response.statusCode}');
    • }
    • } catch (e) {
    • print('错误: $e');
    • }
    • }

    参考来源:

    https://www.cnblogs.com/zhujiabin/p/10333253.html