Flutter 发送json请求,并解析json数据

Flutter 发送json请求,并解析json数据

这几天看了下Flutter,功能比较强大,但是相关的资料却比较少,网上基本没有发送json数据的,只有解析json数据。特此记录给有需要的同学,避免踩坑在找资料上。
原文链接:https://blog.csdn.net/weixin_44259356/article/details/104424424

get请求,并解析Json

发起gat请求,并解析返回的json数据,显示ip地址。

import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

void main() {
     
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
     
  @override
  Widget build(BuildContext context) {
     
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
     
  MyHomePage({
     Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
     
  var _ipAddress = 'Unknown';

  _getIPAddress() async {
     
    var url = 'https://httpbin.org/ip';
    var httpClient = new HttpClient();

    String result;
    try {
     
      var request = await httpClient.getUrl(Uri.parse(url));
      var response = await request.close();
      if (response.statusCode == HttpStatus.OK) {
     
        var json = await response.transform(utf8.decoder).join();
        var data = jsonDecode(json);
        result = data['origin'];
      } else {
     
        result =
            'Error getting IP address:\nHttp status ${
       response.statusCode}';
      }
    } catch (exception) {
     
      result = 'Failed getting IP address';
    }

    // If the widget was removed from the tree while the message was in flight,
    // we want to discard the reply rather than calling setState to update our
    // non-existent appearance.
    if (!mounted) return;

    setState(() {
     
      _ipAddress = result;
    });
  }

  @override
  Widget build(BuildContext context) {
     
    var spacer = new SizedBox(height: 32.0);

    return new Scaffold(
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text('Your current IP address is:'),
            new Text('$_ipAddress.'),
            spacer,
            new RaisedButton(
              onPressed: _getIPAddress,
              child: new Text('Get IP address'),
            ),
          ],
        ),
      ),
    );
  }
}

发起post Json请求

在以上代码修改如下就行

修改请求头

request.headers.add("Content-Type", "application/json");

增加json数据

  request.add(utf8.encode("\{\"from\"\: \"xxxx\"\,\}"));

修改url

将上面url修改为能接受json请求的任意后台接口就行。

参考链接

https://flutterchina.club/networking/

你可能感兴趣的:(Flutter,Flutter,Post,json,Json,Get,http请求)