zoukankan      html  css  js  c++  java
  • Flutter -------- Http库实现网络请求

    第三方库 http实现网络请求,包含get,post

    http库文档:https://pub.dev/packages/http

    1.添加依赖

    dependencies:
      http: ^0.12.0 #latest version

    2.导入库

    import 'package:http/http.dart' as http; //导入前需要配置

    get

    var data;
    
      _fetchGet() async {
        Map newTitle;
        final response =
            await http.get('https://jsonplaceholder.typicode.com/posts/1');
        final responseJson = json.decode(response.body);
        print("请求成功 ---------- "+responseJson.toString());
        newTitle = responseJson;
    
        setState(() {
          data = newTitle['title'];
          print("title====" + data);
        });
      }

    post

    void _httpPost() async {
        //头部
        var headers = Map<String, String>();
        headers["loginSource"] = "IOS";
        headers["useVersion"] = "3.1.0";
        headers["isEncoded"] = "1";
        headers["bundleId"] = "com.nongfadai.iospro";
        headers["loginSource"] = "IOS";
        headers["Content-Type"] = "application/json";
    
        //参数
    
        Map params = {'v': '1.0','month':'7','day':'25','key':'bd6e35a2691ae5bb8425c8631e475c2a'};
    
        // 嵌套两层都可以,但是具体哪个好还有待确认????
        var jsonParams = utf8.encode(json.encode(params));
        // var jsonParams = json.encode(params);
    
        var httpClient = http.Client();
    
        var uri = Uri.parse("http://api.juheapi.com/japi/toh");
    
        http.Response response =
        await httpClient.post(uri, body: jsonParams, headers: headers);
    
        if (response.statusCode == HttpStatus.ok) {
          print('请求成功');
          print(response.headers);//打印头部信息
          print("post------${response.body}");
        } else {
          print('请求失败 code 码${response.statusCode}');
        }
      }


    调用:

    class HttpMain extends StatefulWidget {
      @override
      createState() => new HttpPage();
    }
    
    class HttpPage extends State<HttpMain> {
    
      @override
      Widget build(BuildContext context) {
        _fetchGet();
        _httpPost();
        return new MaterialApp(
          title: 'Fetch Data Example',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text('Fetch Data Example'),
            ),
            body: new Center(
              child: new Text("$data"),
            ),
          ),
        );
      }
    }

    控制台

    get

    post

  • 相关阅读:
    前端插件集合
    建立controller
    W3C对DOM2.0定义的标准事件
    事件代理和委托学习
    css3属性flex弹性布局设置三列(四列)分布样式
    css+html 关于文本的总结(整理中)
    jquery阻止事件冒泡的3种方式
    web前端打印总结
    前端打印插件
    object实现小老鼠交互
  • 原文地址:https://www.cnblogs.com/zhangqie/p/10871062.html
Copyright © 2011-2022 走看看