1?測試Http和HttpClient
? ?導入包:在pubspec.yaml里面導入
http: ^0.12.2
? main.dart里面導入
?
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';
?
?
?
?
?
?
?
2 代碼實現
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:io';void main() {runApp(MyApp1());
}class MyApp1 extends StatelessWidget {void getWeatherData() async {try {HttpClient httpClient = HttpClient();HttpClientRequest request = await httpClient.getUrl(Uri.parse("http://pv.sohu.com/cityjson?ie=utf-8"));HttpClientResponse response = await request.close();var result = await response.transform(utf8.decoder).join();print(result);httpClient.close();} catch (e) {print("get data fail $e");} finally {}}@overrideWidget build(BuildContext context) {return MaterialApp(title: 'open url',home: Scaffold(appBar: AppBar(// Here we take the value from the MyHomePage object that was created by// the App.build method, and use it to set our appbar title.title: Text('hello flutter'),),body: Center(child: Column(// Column is also a layout widget. It takes a list of children and// arranges them vertically. By default, it sizes itself to fit its// children horizontally, and tries to be as tall as its parent.//// Invoke "debug painting" (press "p" in the console, choose the// "Toggle Debug Paint" action from the Flutter Inspector in Android// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)// to see the wireframe for each widget.//// Column has various properties to control how it sizes itself and// how it positions its children. Here we use mainAxisAlignment to// center the children vertically; the main axis here is the vertical// axis because Columns are vertical (the cross axis would be// horizontal).mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Text('hello word flutter',),RaisedButton(onPressed: () {const url = 'https://www.baidu.com';http.get(url).then((response) {print("狀態 is ${response.statusCode}");print("內容 is ${response.body}");});},child: Text('test Http'),),RaisedButton(onPressed: getWeatherData,child: Text('test HttpClient get weather'),),],),),),);}
}
?
?
?
?
?
?
3 運行結果
點擊test Http日志打印如下
I/flutter (27404): 狀態 is 200
I/flutter (27404): 內容 is <html>
I/flutter (27404): <head>
I/flutter (27404): <script>
I/flutter (27404): location.replace(location.href.replace("https://","http://"));
I/flutter (27404): </script>
I/flutter (27404): </head>
I/flutter (27404): <body>
I/flutter (27404): <noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
I/flutter (27404): </body>
I/flutter (27404): </html>
點擊 test HttpClient get weather日志打印如下
?
I/flutter (27404): var returnCitySN = {"cip": "220.250.29.154", "cid": "350100", "cname": "福建省福州市"};