Flutter网络请求基础教程

完整代码

children: [
              RaisedButton(
                  child: Text("请求百度首页"),
                  onPressed: loading
                      ? null
                      : () async {
                          setState(() {
                            loading = true;
                            result = "请求中.....";
                          });
                          try {
                            //创建HttpClient
                            HttpClient httpClient = new HttpClient();
                            //打开链接
                            HttpClientRequest request = await httpClient.getUrl(Uri.parse("https://www.baidu.com"));
                            //设置UA
                            request.headers.add("user-agent",
                                "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1");
                            //连接服务器
                            HttpClientResponse response = await request.close();
                            //读取响应内容
                            result = await response.transform(utf8.decoder).join();
                            //打印响应头
                            print(response.headers);
                            //关闭client 终止请求
                            httpClient.close();
                          } catch (e) {
                            result = "请求失败:$e";
                          } finally {
                            setState(() {
                              loading = false;
                            });
                          }
                        }),
              Container(
                  width: MediaQuery.of(context).size.width - 50,
                  child: Text(
                    result.replaceAll(new RegExp(r"\s"), ""),
                    style: TextStyle(color: Colors.black),
                  ))
            ],

你可能感兴趣的:(Flutter网络请求基础教程)