今天來講說Flutter中的網絡請求,HttpClient網絡請求,包含get,postjson
getapi
var data; _get() async { Map newTitle; var responseBody; var url = 'https://jsonplaceholder.typicode.com/posts/1'; var httpClient = new HttpClient(); var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); if (response.statusCode == 200) { responseBody = await response.transform(utf8.decoder).join(); responseBody = json.decode(responseBody); print(responseBody.toString()); newTitle = responseBody; print("get:-------${newTitle}"); } else { print("error"); data = "null"; } if (!mounted) return; //狀態管理(該控制的核心在於:回調,更新數據在控件上) /** 有三種方式: 一、Widget本身管理State 二、父類管理State 三、混合管理 */ setState(() { data = newTitle['title']; }); }
post網絡
void _post() async { HttpClient httpClient = new HttpClient(); // queryParameters get請求的查詢參數(適用於get請求???是嗎???) // Uri uri = Uri( // scheme: "https", host: "xxx.xxx.xxx.xxx", path: homeRegularListUrl); // HttpClientRequest request = await httpClient.postUrl(uri); var url = "http://api.juheapi.com/japi/toh"; HttpClientRequest request = await httpClient.postUrl(Uri.parse(url)); // 設置請求頭 /* request.headers.set("loginSource", "IOS"); request.headers.set("useVersion", "3.1.0"); request.headers.set("isEncoded", "1"); // Content-Type大小寫都ok request.headers.set('content-type', 'application/json');*/ /// 添加請求體 Map jsonMap = {'shopperId': 9356,'machineId':5117,'orderType':2,'orderId':108}; Map<String, String> map1 = new Map(); map1["v"] = "1.0"; map1["month"] = "7"; map1["day"] = "25"; map1["key"] = "bd6e35a2691ae5bb8425c8631e475c2a"; request.add(utf8.encode(json.encode(map1))); HttpClientResponse response = await request.close(); String responseBody = await response.transform(utf8.decoder).join(); if (response.statusCode == HttpStatus.ok) { print('請求成功'); print(response.headers);//打印頭部信息 print("post------${responseBody}"); } }
調用:app
class HttpClientMain extends StatefulWidget { @override createState() => new HttpClientHttp(); } class HttpClientHttp extends State<HttpClientMain> { @override Widget build(BuildContext context) { _get(); _post(); return Scaffold( appBar: new AppBar( title: new Text("net"), ), //body: new MyHomePage() body: new Center( child: new Text("$data"), ), ); } }
控制檯打印async
get:ide
post:post