flutter 访问网页+http请求

一、目录

1、访问网页

2、http请求

-----------------------------这是分割线-----------------------------

1、访问网页

 基于url_launcher库实现,最新版本号 5.0.2,没有的话需要添加到pubspec.yaml中

然后get 该package

只要引入不报错就ok了。

ex.dart

/*
  time: 2019-4-3
 */

// 引入资源包
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

// main fun
void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
        title: 'url请求',
        home: new Scaffold(
          appBar: new AppBar(
            title: new Text('Example of packages'),
          ),
          body: new Center(
            child: new RaisedButton(
              onPressed: () {
                print(1);
                // url
                const url = "https://www.baidu.com";
                launch(url); // 打开浏览器跳转至百度网页
              },
              child: new Text('baidu'),
            ),
          ),
        ));
  }
}

运行效果如下

点击baidu按钮,打开网页

2、http请求

2.1、Http请求

下载Http库 版本号 0.12.0+2

ex.dart

/*
  time: 2019-4-3
  title: htttp请求
 */

// 引入资源包
import 'package:flutter/material.dart';
//import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;

// main fun
void main () => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
        title: 'Http 请求示例',
        home: new Scaffold(
          appBar: new AppBar(
            title:  new Text('Http 请求示例'),
          ),
          body: new Center(
            child: new RaisedButton(
              onPressed: () {
                print(1);
                var url = 'http://www.cnblogs.com/';

                // get
                http.get(url).then((response) {
                  print("Response status: ${response.statusCode}");
                  print("Response body: ${response.body[10]}");
                });

                // post
                http.post(url,body: {"key": "value"}).then((response) {
                  print('this is post');
                  print("Response status: ${response.statusCode}");
                  print("Response body: ${response.body}");
                });
              },
              child: new Text('发送请求'),
            ),
          ),
        )
    );
  }
}

运行效果

我点击发送请求之后,控制台输出

请求成功,并返回了内容。

2.1、HttpClient请求

 ex.dart

/*
  time: 2019-4-3
  title: htttpClient请求
 */

// 引入资源包
import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';

// main fun
void main () => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // 获取天气数据
  void getWeatherData() async {
    try {
      // 实例化一个HttpCLient对象
      HttpClient  httpClient = new HttpClient();

      // 发起请求
      HttpClientRequest request = await httpClient.getUrl(
          Uri.parse("http://wthrcdn.etouch.cn/weather_mini?city=重庆市")
      );
      // 等待服务器返回数据
      HttpClientResponse response = await request.close();
      // 使用utf-8.decoder从response解析数据
      var result = await response.transform(utf8.decoder).join();
      // 输出
      print(result);
      // 关闭
      httpClient.close();

    } catch (e) {
      print("请求失败:$e");
    }
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new MaterialApp(
      title: 'HttpClient 请求示例',
      home: new Scaffold(
        appBar: new AppBar(
          title:  new Text('HttpClient 请求示例'),
        ),
        body: new Center(
          child: new RaisedButton(
              onPressed: getWeatherData,
              child: new Text('获取天气数据'),
          ),
        ),
      )
    );
  }
}

运行效果如下:

点击按钮之后,控制台输出:

I/flutter (15353): {"data":{"yesterday":{"date":"6日星期六","high":"高温 30℃","fx":"无持续风向","low":"低温 14℃","fl":"<![CDATA[<3级]]>","type":"晴"},"city":"重庆","forecast":[{"date":"7日星期天","high":"高温 32℃","fengli":"<![CDATA[<3级]]>","low":"低温 15℃","fengxiang":"无持续风向","type":"晴"},{"date":"8日星期一","high":"高温 32℃","fengli":"<![CDATA[<3级]]>","low":"低温 18℃","fengxiang":"无持续风向","type":"多云"},{"date":"9日星期二","high":"高温 29℃","fengli":"<![CDATA[<3级]]>","low":"低温 19℃","fengxiang":"无持续风向","type":"多云"},{"date":"10日星期三","high":"高温 24℃","fengli":"<![CDATA[<3级]]>","low":"低温 18℃","fengxiang":"无持续风向","type":"阴"},{"date":"11日星期四","high":"高温 25℃","fengli":"<![CDATA[<3级]]>","low":"低温 18℃","fengxiang":"无持续风向","type":"多云"}],"ganmao":"各项气象条件适宜,发生感冒机率较低。但请避免长期处于空调房间中,以防感冒。","wendu":"3}

猜你喜欢

转载自www.cnblogs.com/shuangzikun/p/10665520.html