今天来说说Flutter中的网络请求,HttpClient网络请求,包含get,post
get
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; //状态管理(该控制的核心在于:回调,更新数据在控件上) /** 有三种方式: 1、Widget自己管理State 2、父类管理State 3、混合管理 */ 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}; Mapmap1 = 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}"); } }
调用:
class HttpClientMain extends StatefulWidget { @override createState() => new HttpClientHttp();}class HttpClientHttp extends State{ @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"), ), ); }}
控制台打印
get:
post: