發起HTTP請(qǐng)求
http支持位于dart:io,所以要(yào)創建一(yī)個HTTP client, 我們需要(yào)添加一(yī)個導入:
import 'dart:io';
var httpClient = new HttpClient();
該 client 支持常用的HTTP操作(zuò), such as GET, POST, PUT, DELETE.
處理異步
注意,HTTP API 在返回值中使用了(le)Dart Futures。 我們建議(yì)使用async/await語法來調用API。
網絡調用通(tōng)常遵循如(rú)下(xià)步驟:
創建 client.
構造 Uri.
發起請(qǐng)求, 等待請(qǐng)求,同時(shí)您也可(kě)以配置請(qǐng)求headers、 body。
關閉請(qǐng)求, 等待響應.
解碼響應的內(nèi)容.
Several of these steps use Future based APIs. Sample APIs calls for each step above are: 其中的幾個步驟使用基于Future的API。上(shàng)面步驟的示例:
get() async {
var httpClient = new HttpClient();
var uri = new Uri.http(
'example.com', '/path1/path2', {'param1': '42', 'param2': 'foo'});
var request = await httpClient.getUrl(uri);
var response = await request.close();
var responseBody = await response.transform(UTF8.decoder).join();
}
有關完整的代碼示例,請(qǐng)參閱下(xià)面的“示例”。
解碼和(hé)編碼JSON
使用dart:convert庫可(kě)以簡單解碼和(hé)編碼JSON。 有關其他(tā)的JSON文檔,請(qǐng)參閱JSON和(hé)序列化。
解碼簡單的JSON字符串并将響應解析為(wèi)Map:
Map data = JSON.decode(responseBody);
// Assume the response body is something like: ['foo', { 'bar': 499 }]
int barValue = data[1]['bar']; // barValue is set to 499
要(yào)對簡單的JSON進行(xíng)編碼,請(qǐng)将簡單值(字符串,布爾值或數(shù)字字面量)或包含簡單值的Map,list等傳給encode方法:
String encodedString = JSON.encode([1, 2, { 'a': null }]);
示例: 解碼 HTTPS GET請(qǐng)求的JSON
以下(xià)示例顯示了(le)如(rú)何在Flutter應用中對HTTPS GET請(qǐng)求返回的JSON數(shù)據進行(xíng)解碼
It calls the httpbin.com web service testing API, which then responds with your local IP address. Note that secure networking (HTTPS) is used. 它調用httpbin.comWeb service測試API,請(qǐng)注意,使用安全網絡請(qǐng)求(HTTPS)
運行(xíng)flutter create,創建一(yī)個新的Flutter應用.
将lib/main.dart替換為(wèi)一(yī)下(xià)內(nèi)容:
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State
var _ipAddress = 'Unknown';
_getIPAddress() async {
var url = 'https://httpbin.org/ip';
var httpClient = new HttpClient();
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(utf8.decoder).join();
var data = jsonDecode(json);
result = data['origin'];
} else {
result =
'Error getting IP address:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed getting IP address';
}
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;
setState(() {
_ipAddress = result;
});
}
@override
Widget build(BuildContext context) {
var spacer = new SizedBox(height: 32.0);
return new Scaffold(
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children:
new Text('Your current IP address is:'),
new Text('$_ipAddress.'),
spacer,
new RaisedButton(
onPressed: _getIPAddress,
child: new Text('Get IP address'),
),
],
),
),
);
}
}
網站建設開(kāi)發|APP設計開(kāi)發|小程序建設開(kāi)發