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技術入門與實戰》

以上純屬個人見解,本人小白一個,如有錯誤,請大佬指教。 

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