Flutter之测试Http和HttpClient

简介: 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 运行结果

20200814165409295.png

点击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": "福建省福州市"};
相关文章
|
3月前
|
JSON 搜索推荐 网络协议
玩转curl指令—测试简单的HTTP接口
玩转curl指令—测试简单的HTTP接口
63 0
|
4月前
阿萨聊测试:如何用Postman查看HTTP消息相关内容?
阿萨聊测试:如何用Postman查看HTTP消息相关内容?
阿萨聊测试:如何用Postman查看HTTP消息相关内容?
|
7天前
|
缓存 监控 前端开发
【Flutter前端技术开发专栏】Flutter应用的性能调优与测试
【4月更文挑战第30天】本文探讨了Flutter应用的性能调优策略和测试方法。性能调优对提升用户体验、降低能耗和增强稳定性至关重要。优化布局(避免复杂嵌套,使用`const`构造函数)、管理内存、优化动画、实现懒加载和按需加载,以及利用Flutter的性能工具(如DevTools)都是有效的调优手段。性能测试包括基准测试、性能分析、压力测试和电池效率测试。文中还以ListView为例,展示了如何实践这些优化技巧。持续的性能调优是提升Flutter应用质量的关键。
【Flutter前端技术开发专栏】Flutter应用的性能调优与测试
|
7天前
|
前端开发 测试技术 持续交付
【Flutter 前端技术开发专栏】Flutter 中的 UI 测试与自动化测试
【4月更文挑战第30天】本文探讨了 Flutter 应用中UI测试和自动化测试的重要性,包括保障质量、提高效率和增强开发信心。Flutter提供`flutter_test`库进行Widget测试,以及`flutter_driver`进行集成测试。UI测试涵盖界面布局、交互和状态变化的验证,最佳实践建议尽早引入测试、保持用例简洁,并结合手动测试。未来,随着Flutter技术发展,UI测试和自动化测试将更加完善,助力开发高质量应用。
【Flutter 前端技术开发专栏】Flutter 中的 UI 测试与自动化测试
|
7天前
|
JSON Java Apache
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
|
9天前
|
弹性计算 运维 监控
|
11天前
|
存储 缓存 开发框架
Flutter的网络请求:使用Dart进行HTTP请求的技术详解
【4月更文挑战第26天】了解Flutter网络请求,本文详述使用Dart进行HTTP请求
|
13天前
|
JSON 测试技术 API
Python的Api自动化测试使用HTTP客户端库发送请求
【4月更文挑战第18天】在Python中进行HTTP请求和API自动化测试有多个库可选:1) `requests`是最流行的选择,支持多种请求方法和内置JSON解析;2) `http.client`是标准库的一部分,适合需要低级别控制的用户;3) `urllib`提供URL操作,适用于复杂请求;4) `httpx`拥有类似`requests`的API,提供现代特性和异步支持。根据具体需求选择,如多数情况`requests`已足够。
15 3
|
15天前
Swagger基本使用与RestTemplate发送http接口测试
Swagger基本使用与RestTemplate发送http接口测试
20 1
|
21天前
|
安全 网络安全 开发工具
对象存储oss使用问题之flutter使用http库进行post请求文件上传返回400如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
39 1