Flutter之测试Http和HttpClient
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 {
}
}
@override
Widget 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": "福建省福州市"};
赞 (0)