flutter HttpClient示例

class HttpClientWidget extends StatefulWidget {
  const HttpClientWidget({super.key});

  @override
  State<HttpClientWidget> createState() {
    return HttpClientState();
  }
}

class HttpClientState extends State<HttpClientWidget> {
  bool _loading = false;
  String _text = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("HttpClient")),
      body: SingleChildScrollView(
        child: Column(children: <Widget>[
          ElevatedButton(
            onPressed: _loading ? null : request,
            child: const Text("获取百度首页"),
          ),
          SizedBox(
            width: MediaQuery.of(context).size.width - 50.0,
            child: Text(_text.replaceAll(RegExp(r"\s"), "")),
          ),
        ]),
      ),
    );
  }

  request() async {
    setState(() {
      _loading = true;
      _text = "正在请求中...";
    });

    try {
      //创建一个HttpClient
      HttpClient httpClient = HttpClient();
      //打开Http连接
      HttpClientRequest request =
          await httpClient.getUrl(Uri.parse("https://www.baidu.com"));

      //使用iPhone的UA
      request.headers.add("user-agent",
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");

      //等待连接服务器(会将请求信息发送给服务器)
      HttpClientResponse response=await request.close();
      //读取相应内容
      _text=await response.transform(utf8.decoder).join();
      //输出响应头
      print(response.headers);

      //关闭client后,通过该client发起的所有请求都会中止。
      httpClient.close();
    } catch (e) {
      _text = "请求失败:$e";
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }
}

猜你喜欢

转载自blog.csdn.net/xiaopihair123/article/details/125188714