flutter中http进行网络请求

flutter中http进行网络请求,第1张

一.flutter 网络请求的三种方式

1.HttpClient请求

实现步骤:

1).导入包

import 'dart:convert';
import 'dart:io';

2).创建HttpClient

var httpClient=HttpClient();

3). Http连接,并获取解析url

var request=await httpClient.getUrl(Uri.parse(url));

 这里可以附加参数,并通过HttpClientRequest设置请求header,eg:

Uri uri = Uri(scheme: "https", host: "flutterchina.club", queryParameters: {
    "name":"jon",
    "pwd":"1234"
  });
request.headers.add("user-agent", "test");

此处也可设置 Get 请求、Post 请求、Put 请求、Delete 请求,eg :源码

/**
   * Opens a HTTP connection using the GET method.
   *
   * The server is specified using [host] and [port], and the path
   * (including a possible query) is specified using
   * [path].
   *
   * See [open] for details.
   */
  Future get(String host, int port, String path);

  /**
   * Opens a HTTP connection using the GET method.
   *
   * The URL to use is specified in [url].
   *
   * See [openUrl] for details.
   */
  Future getUrl(Uri url);

  /**
   * Opens a HTTP connection using the POST method.
   *
   * The server is specified using [host] and [port], and the path
   * (including a possible query) is specified using
   * [path].
   *
   * See [open] for details.
   */
  Future post(String host, int port, String path);

  /**
   * Opens a HTTP connection using the POST method.
   *
   * The URL to use is specified in [url].
   *
   * See [openUrl] for details.
   */
  Future postUrl(Uri url);

  /**
   * Opens a HTTP connection using the PUT method.
   *
   * The server is specified using [host] and [port], and the path
   * (including a possible query) is specified using [path].
   *
   * See [open] for details.
   */
  Future put(String host, int port, String path);

  /**
   * Opens a HTTP connection using the PUT method.
   *
   * The URL to use is specified in [url].
   *
   * See [openUrl] for details.
   */
  Future putUrl(Uri url);

  /**
   * Opens a HTTP connection using the DELETE method.
   *
   * The server is specified using [host] and [port], and the path
   * (including a possible query) is specified using [path].
   *
   * See [open] for details.
   */
  Future delete(String host, int port, String path);

  /**
   * Opens a HTTP connection using the DELETE method.
   *
   * The URL to use is specified in [url].
   *
   * See [openUrl] for details.
   */
  Future deleteUrl(Uri url);

4).关闭请求, 等待响应

var response=await request.close();

5).解码响应的内容

if(response.statusCode==HttpStatus.ok){
        var json=await response.transform(utf8.decoder).join();

2.http库请求

1).  pubspec.yaml 中添加依赖包

dependencies:
  flutter:
    sdk: flutter

    http: '>=0.11.3+12'

2). 代码中导入包

import 'package:http/http.dart' as http;

3).get,post实现

void getRequest() async {
    var client = http.Client();
    http.Response response = await client.get(url);
    _ipAddress = response.body;
  }

void postRequest() async {
    var params = Map();
    params["name"] = "jon";
    params["pwd"] = "1234";

    var client = http.Client();
    var response = await client.post(uri, body: params);
    _ipAddress = response.body;
  }

3.第三方库dio请求

1).参考dio4.0.4

2).参考上一篇:获取flutter中最新的依赖包

二.HttpClient 实现demo展示

class getIpPage extends StatefulWidget{
  @override
  State createState()=> _getIpPageState();
}

class _getIpPageState extends State{
  var _ipAddress="192.168.0.1";

  _getIpAddress() async{
    var url='https://httpbin.org/ip';
    var httpClient=HttpClient();
    String ipResult;
    try{
      var request=await httpClient.getUrl(Uri.parse(url));
      var response=await request.close();
      if(response.statusCode==HttpStatus.ok){
        var json=await response.transform(utf8.decoder).join();
        var data=jsonDecode(json);
        ipResult=data['origin'];
      }else{
        ipResult =
        'Error getting IP address,Http status is: ${response.statusCode}';
      }
      
    }catch(exception){
      ipResult = 'Exception,Failed getting IP address';
    }

    setState(() {
      _ipAddress=ipResult;
    });
  }
  

  @override
  Widget build(BuildContext context) {
    var stack = Stack(
      alignment: Alignment.center,
      children: [
        Container(
          decoration: const BoxDecoration(
            color: Colors.black45,
          ),
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Current IP address is: $_ipAddress.',
                style: const TextStyle(
                  fontSize: 12.0,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              RaisedButton(
                onPressed: _getIpAddress,
                child: new Text('Get IP address'),
              ),
            ],
          )
        ),
      ],
    );

    return stack;
  }

}

三.效果展示

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/996701.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存