首頁>其它>

此答案說明Dart團隊如何使用http包發出HTTP請求,

我們將使用JSONPlaceholder作為API示例,大家可以看看格式如下

GET / posts GET / posts / 1 GET / posts / 1 / comments GET / comments?postId = 1 GET / posts?userId = 1 POST / posts PUT / posts / 1 PATCH / posts / 1 DELETE / posts / 1

我們先來新增一個網路請求框架到專案裡面

dependencies:  http: ^0.12.0+4

當我們要在專案檔案裡面使用網路的時候,需要匯入這個框架的API包:

import 'package:http/http.dart';

接下來我寫個簡單的API請求,GET請求,大家可以看看

_makeGetRequest() async {  String url = 'https://jsonplaceholder.typicode.com/posts';  Response response = await get(url);  int statusCode = response.statusCode;  Map<String, String> headers = response.headers;  String contentType = headers['content-type'];  String json = response.body;}

可以使用dart:convert將介面返回的資料轉換成你想要的物件。

_makePostRequest() async {  // 設定POST請求引數  String url = 'https://jsonplaceholder.typicode.com/posts';  Map<String, String> headers = {"Content-type": "application/json"};  String json = '{"title": "Hello", "body": "body text", "userId": 1}';  // 發出POST請求  Response response = await post(url, headers: headers, body: json);  // 檢查結果的狀態碼  int statusCode = response.statusCode;  String body = response.body;  // {  //   "title": "Hello",  //   "body": "body text",  //   "userId": 1,  //   "id": 101  // }}

這節課就講解到這裡吧,一個簡單的get,post請求就完成了,Flutter網路請求你學會了嗎?

27
最新評論
  • 康明斯6bt發動機
  • 國產手機集體開始"果化"