[Flutter]發出HTTP請求獲取數據

最後更新於 2021 年 3 月 12 日

最近在寫一個基於flutter框架的APP,APP所要呈現的內容需要通過API串接獲取,所以需要使用到http這個庫,那就說說我是怎麼實現的吧。

安裝及導入庫

http | dart package : https://pub.dev/packages/http

1.在 pubspec.yaml 文件中加上

dependencies:
  http: ^0.12.2

2.導入庫

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

使用方法

example/main.dart

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
void main(List<String> arguments) async {
  // This example uses the Google Books API to search for books about http.
  // https://developers.google.com/books/docs/overview
  var url = 'https://www.googleapis.com/books/v1/volumes?q={http}';
  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse = convert.jsonDecode(response.body);
    var itemCount = jsonResponse['totalItems'];
    print('Number of books about http: $itemCount.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

API串接

用農產品行情API做範例(https://agridata.coa.gov.tw/api.aspx)

20210130101130 [Flutter]發出HTTP請求獲取數據

我們可以拿到的API request URL格式為

https://agridata.coa.gov.tw/api/v1/AgriProductsTransType/?Start_time=開始時間&End_time=結束時間&api_key=你的API

20210130101404 [Flutter]發出HTTP請求獲取數據

值得注意的是這個網址的格式’日期‘是可變動的,API則可固定不變,所以我們需要使用到DateTime

var now = new DateTime.now();
print(now); //2021-1-30 18:20:44.605510

但是DateTime產生的是 西元 的日期而非民國,這個API的網址格式年分使用的是 民國,所以我們需要將年份減去1911來獲得正確的網址格式

DateTime today = new DateTime.now();
String now ="${(today.year-1911).toString()}.${today.month.toString().padLeft(2,'0')}.${today.day.toString().padLeft(2,'0')}";
var url = 'https://agridata.coa.gov.tw/api/v1/AgriProductsTransType/?Start_time=${now}&End_time=${now}&api_key=你的API';

部分程式碼

void main(List<String> arguments) async {
  //Request URL
  DateTime today = new DateTime.now();
  String now ="${(today.year-1911).toString()}.${today.month.toString().padLeft(2,'0')}.${today.day.toString().padLeft(2,'0')}";
  var url = 'https://agridata.coa.gov.tw/api/v1/AgriProductsTransType/?Start_time=${now}&End_time=${now}&api_key=你的API';
  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    var jsonResponse = convert.jsonDecode(response.body);
    var itemCount = jsonResponse['Data'];
    ...
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}
0 0 評分數
Article Rating
訂閱
通知
guest

0 Comments
在線反饋
查看所有評論