Flutter开发之HTTP网络请求:Http库(27)

第三方库 http实现get,post网络请求。
http库文档地址:https://pub.dev/packages/http#-installing-tab-

添加依赖库

  1. Add this to your package’s pubspec.yaml file:
dependencies:
  http: ^0.12.0+2
  1. You can install packages from the command line:
$ flutter pub get
  1. 查看插件安装成功与否:左侧http-0.12.0+2包出现
    Flutter开发之HTTP网络请求:Http库(27)_第1张图片

导入库

import 'package:http/http.dart' as http;

Get、Post请求示例

页面包涵两个按钮:分别触发_get()、_post() 函数。

Flutter开发之HTTP网络请求:Http库(27)_第2张图片
页面代码如下:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';

_get() async {
  print("_get---");

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

  data = newTitle['title'];
  print("title====" + data);
}



_post() async {

  print("_post---");

  //头部
  var headers = Map();
  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 httpObj = http.Client();

  var uri = Uri.parse("http://api.juheapi.com/japi/toh");

  http.Response response =
  await httpObj.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 HttpLibTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Http库Test'),
      ),

      body: Center(
        child:Column(

          children: [

            SizedBox(height: 32.0),

            Text("Http库Test Get Post 练习"),

            SizedBox(height: 32.0),

            RaisedButton(
              onPressed: _get,
              child: new Text('Get 请求'),
            ),


            RaisedButton(
              onPressed: _post,
              child: new Text('Post 请求'),
            ),

          ],

        ),
      ),


    );
  }
}

触发_get()的结果
在这里插入图片描述
触发_post()的结果
Flutter开发之HTTP网络请求:Http库(27)_第3张图片

特别感谢:
Flutter -------- Http库实现网络请求

你可能感兴趣的:(Flutter开发教程)