dart原生請求

庚中發表於2020-12-08

系統內建庫請求方式:

import 'dart:io'; //內含HttpClient函式

import 'dart:convert'; //帶utf-8內建物件

void main() async {
  var result = await getDataFromZhihuAPI();
  print("$result 請求結果");
}

//api介面: http://news-at.zhihu.com/api/3/stories/latest
getDataFromZhihuAPI() async {
  //1、建立HttpClient物件
  var httpClient = new HttpClient();
  //2、建立Uri物件
  var uri = new Uri.http('news-at.zhihu.com', 'api/3/stories/latest');

  //3、發起請求,等待請求
  var request = await httpClient.getUrl(uri);
  //4、關閉請求,等待響應
  var response = await request.close();
  //5、解碼響應的內容
  return await response.transform(utf8.decoder).join();
}

相關文章