上節課代碼清楚 從新編寫HomePage這個動態組件json
開始寫請求的方法app
請求數據 。可是因爲咱們沒加請求的頭 因此沒有返回數據async
451就是表示請求錯錯誤ide
注意這裏是Request Headers這塊纔是請求頭ui
把請求頭所有複製過來。spa
而後給這些數據 都加上單引號,作成mapper的形式。3d
在VScode裏面按住鼠標的alt鍵就能夠多選code
把這些字母的最前面和最後面都加上光標,而後鼠標再輸入單引號blog
這樣單引號就都加上了。ip
把這些參數都放在了單引號裏面,而且後面加上了逗號
糾正一個地方,config文件夾是在lib的文件夾下面的
在咱們的首頁裏面引入請求頭的dart文件
而後只須要在請求以前設置請求頭就能夠了
httpHeaders.dart
const httpHeaders={ 'Accept': 'application/json, text/plain', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Cookie': '_ga=GA1.2.381584897.1534769652; Hm_lvt_022f847c4e3acd44d4a2481d9187f1e6=1552920445,1553872955,1553873168,1554093939; _gid=GA1.2.335717019.1554093939; SERVERID=3431a294a18c59fc8f5805662e2bd51e|1554094392|1554093939; Hm_lpvt_022f847c4e3acd44d4a2481d9187f1e6=1554094392; _gat=1', 'Host': 'time.geekbang.org', 'Origin': 'https://time.geekbang.org', 'Referer': 'https://time.geekbang.org/', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36' };
home_page.dart
import 'package:flutter/material.dart'; import 'package:dio/dio.dart'; import '../config/httpHeaders.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { String showText='尚未請求數據'; @override Widget build(BuildContext context) { return Container( child: Scaffold( appBar: AppBar(title: Text('請求遠程數據'),), body: SingleChildScrollView( child: Column( children: <Widget>[ RaisedButton( onPressed: _jike, child:Text('請求數據') ), Text(showText) ], ), ), ), ); } void _jike(){ print('開始想極客時間請求數據..........'); getHttp().then((val){ setState(() { showText=val['data'] .toString(); }); }); } Future getHttp() async{ try { Response response; Dio dio=new Dio(); dio.options.headers=httpHeaders;//設置請求頭 response=await dio.get('https://time.geekbang.org/serv/v1/column/newAll'); print(response); return response.data; } catch (e) { return print(e); } } }