Flutter中的网络请求

Flutter请求网络有两种方法,一种是Http请求,另一种是HttpClient请求

1.Http请求方式

使用Http方式请求网络时,需要导入Http包。如下所示

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

2.HttpClient请求方式

使用HttpClient方式请求网络时,需要导入io以及convert包。如下所示

import 'dart:convert';
import 'dart:io';

请看以下完整代码

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

/**
 * 作者:BecauseHappy
 * 时间:20191014
 */
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  /*创建client实例*/
  var httpClient = new HttpClient();
  /*baseURL*/
  static final menuBaseUri = "http://apis.juhe.cn/cook/query";
  /*get请求URL*/
  var menuGetUri =
      menuBaseUri + "?key=bb0dea24e1450f40835a081685006145&menu=西红柿炒鸡蛋";
  var logger = Logger(
    printer: PrettyPrinter(),
  );

  /*发送HttpClient POST请求*/
  httpClientPostUrl() async {
    try {
      /*发起发送HttpClient请求*/
      HttpClientRequest httpClientRequest =
          await httpClient.postUrl(Uri.parse(menuGetUri));
      /*设置body参数*/
      Map<String, String> bodyParams = new Map();
      bodyParams["key"] = "bb0dea24e1450f40835a081685006145";
      bodyParams["menu"] = "西红柿炒鸡蛋";
      /*添加body参数*/
      httpClientRequest.add(utf8.encode(json.encode(bodyParams)));
      /*等待服务器返回*/
      HttpClientResponse httpClientResponse = await httpClientRequest.close();
      /*使用utf8.decoder从httpClientResponse里解析数据*/
      var result = await httpClientResponse.transform(utf8.decoder).join();
      /*打印返回数据*/
      logger.d("请求成功:${result.toString()}");
      /*关闭发送HttpClient请求*/
      httpClient.close();
    } catch (error) {
      /*请求失败*/
      logger.e("请求失败${error.toString()}");
    }
  }

  /*发送HttpClientGet请求*/
  httpClientGetUrl() async {
    try {
      /*发起发送HttpClient请求*/
      HttpClientRequest httpClientRequest =
          await httpClient.getUrl(Uri.parse(menuGetUri));
      /*等待服务器返回*/
      HttpClientResponse httpClientResponse = await httpClientRequest.close();
      /*使用utf8.decoder从httpClientResponse里解析数据*/
      var result = await httpClientResponse.transform(utf8.decoder).join();
      /*打印返回数据*/
      logger.d("请求成功:${result.toString()}");
      /*关闭发送HttpClient请求*/
      httpClient.close();
    } catch (error) {
      /*请求失败*/
      logger.e("请求失败${error.toString()}");
    }
  }

  /*发送Http Get请求*/
  httpGetUrl() {
    http.get(menuGetUri).then((response) {
      /*请求成功*/
      logger.d("请求成功:${response.body}");
    }).catchError((error) {
      /*请求失败*/
      logger.e("请求失败${error.toString()}");
    });
  }

  /*发送Http post请求*/
  httpPostUrl() {
    //设置body参数
    Map<String, String> bodyParams = new Map();
    bodyParams["key"] = "bb0dea24e1450f40835a081685006145";
    bodyParams["menu"] = "西红柿炒鸡蛋";
    http
        .post(menuBaseUri, body: bodyParams, encoding: Utf8Codec())
        .then((response) {
      /*请求成功*/
      logger.d("请求成功:${response.body}");
    }).catchError((error) {
      /*请求失败*/
      logger.e("请求失败${error.toString()}");
    });
  }
  /*布局*/
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('网络请求实例'),
        ),
        body: Center(
            child: RaisedButton(
          child: Text('发送请求'),
          onPressed: httpClientGetUrl,
        )),
      ),
    );
  }
}

本系列文章是自己阅读 亢少军老师 的《Flutter技术入门与实战》

以上纯属个人见解,本人小白一个,如有错误,请大佬指教。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章