美文网首页
http请求的两种方式

http请求的两种方式

作者: 追风筝的Hassan | 来源:发表于2020-01-02 15:36 被阅读0次

Http协议通常用于前后端的数据交互;flutter请求网络分为两种方式(一)http请求;(二)httpClient请求
http请求首先在pubspec.yaml中引入依赖,然后导入import导入http

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

void main() => runApp(MyApp());

//MyApp不需要做状态处理,所以此组件继承StatelessWidget即可
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //此组件是整个应用的主组件
    return new MaterialApp(
      title: 'http请求示例',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('http请求示例'),
        ),
        body: new Center(
          child: new RaisedButton(
            onPressed: () {
              //指定url并发起请求
              const url = 'https://httpbin.org/';
              //向https://httpbin.org/发起get请求
              http.get(url).then((response) {
                print("状态: ${response.statusCode}");
                print("正文:${response.body}");
              });
            },
            child: new Text('发起http请求'),
          ),
        ),
      ),
    );
  }
}

打印出的http请求信息为


http.png

2.httpClient请求方式

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

void main() => runApp(MyApp());

//MyApp不需要做状态处理,所以此组件继承StatelessWidget即可
class MyApp extends StatelessWidget {
  //获取天气数据
  void getWeatherData() async {
    try {
      //实例化一个httpClient对象
      HttpClient httpClient = new HttpClient();
      //发起请求
      HttpClientRequest request = await httpClient.getUrl(
          Uri.parse("http://t.weather.sojson.com/api/weather/city/101030100"));
      //等待服务器返回数据
      HttpClientResponse response = await request.close();
      //使用utf8.decoder从response解析数据
      var result = await response.transform(utf8.decoder).join();
      //输出响应头
      print(result);
      //httpClient关闭
      httpClient.close();
    } catch (e) {
      print('请求失败: $e');
    } finally {}
  }

  Widget build(BuildContext context) {
    //此组件是整个应用的主组件
    return new MaterialApp(
      title: 'http请求示例',
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('httpClient请求示例'),
        ),
        body: new Center(
          child: new RaisedButton(
            onPressed: getWeatherData,
            child: new Text('获取天气数据'),
          ),
        ),
      ),
    );
  }
}

如果你的请求中需要带参数,可以在uri中添加参数

  Uri uri = Uri(
          scheme: 'https',
          host: 't.weather.sojson.com',
          queryParameters: {
            "_id": 26,
            "city_code": '101030100',
            "city_name": '天津'
          });

相关文章

网友评论

      本文标题:http请求的两种方式

      本文链接:https://www.haomeiwen.com/subject/zvcooctx.html