Flutter之测试Http和HttpClient

该博客介绍了如何在Flutter中使用HttpClient从指定URL获取天气数据。首先,在pubspec.yaml中引入http包,然后在main.dart中导入相关库。通过创建HttpClient对象,发起GET请求到指定API,读取响应并打印结果。代码示例展示了获取和处理HTTP响应的基本步骤。
摘要由CSDN通过智能技术生成

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.
                   

更多请见:http://www.mark-to-win.com/tutorial/51859.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值