Dart的HTTP請求和響應(1)
阿新 • • 發佈:2019-01-05
GET請求
import 'package:http/http.dart' as http;
main(List<String> arguments) {
var url = 'http://httpbin.org/';
//向指定URL傳送GET請求
http.get(url).then((response) {
print("響應狀態: ${response.statusCode}");
print("響應正文: ${response.body}");
});
}
程式碼很簡單,效果如下
POST請求
import 'package:http/http.dart' as http;
main(List<String> arguments) {
var url = 'http://httpbin.org/post';
//向指定URL傳送帶引數的POST請求
http.post(url ,body: 'name=doodle&color=blue').then((response) {
print("響應狀態: ${response.statusCode}");
print("響應正文: ${response.body}");
});
}
這也很簡單,效果如下
展示JSON資料
import 'dart:convert' ;
import 'package:http/http.dart' as http;
main(List<String> arguments) {
var url = 'https://api.github.com/users/dart-lang/repos';
http.get(url ,headers : {'User-Agent':'Dart/1.0(My Dart client)'}).then((response) {
//解析響應字串,並生成Json物件
List<String> repos = JSON.decode(response.body);
//輸出說明字串
var heading = 'Repository | Star count | Fork count';
print(heading);
//輸出與說明字串等長的‘=’字串
print(new List.filled(heading.length, '=').join());
//迴圈輸出Json物件的指定引數
for (var repo in repos) {
print(
"${repo['name']} | "
"${repo['stargazers_count']} | "
"${repo['forks_count']}");
}
});
}
先來看看裡面的JSON字串
暈了沒,再看看程式碼執行後展示的部分JSON資料
這樣就好看多了