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

发布了330 篇原创文章 · 获赞 174 · 访问量 62万+

猜你喜欢

转载自blog.csdn.net/DickyQie/article/details/90274076