Skip to content
章节导航

Flutter 网络开发实战应用(基于 http 实现 post 操作与 json 解析)

发送 x-www-form-urlencoded 格式请求

shell
///发送Post请求
  _doPost() async {
    var uri = Uri.parse('https://api.geekailab.com/uapi/test/test');
    var params = {"requestPrams": "doPost"}; //数据格式要为Map<String, String>
    var response =
        await http.post(uri, body: params); //默认为x-www-form-urlencoded 格式
    //http请求成功
    if (response.statusCode == 200) {
      setState(() {
        resultShow = response.body;
      });
    } else {
      setState(() {
        resultShow = "请求失败:code: ${response.statusCode},body:${response.body}";
      });
    }
  }

发送 json 格式的请求

shell
///发送Json类型的Post请求
  _doPostJson() async {
    var uri = Uri.parse('https://api.geekailab.com/uapi/test/testJson');
    var params = {"requestPrams": "doPost"};
    var response = await http.post(uri,
        body: jsonEncode(params), //将数据转成string
        headers: {
          //设置content-type为application/json
          "content-type": "application/json"
        });
    //http请求成功
    if (response.statusCode == 200) {
      setState(() {
        resultShow = response.body;
      });
      var map = jsonDecode(response.body);
      setState(() {
        resultShow2 = map['msg'];
      });
    } else {
      setState(() {
        resultShow = "请求失败:code: ${response.statusCode},body:${response.body}";
      });
    }
  }

重点:
1、转 json 字符串 jsonEncode(params)
2、设置请求头:"content-type": "application/json"

解析 json

shell
jsonDecode(response.body)