Flutter开发之HTTP网络请求:HttpClient(26)

本文根据 在Flutter中发起HTTP网络请求 编写

对于入门的同学来说,使用的是用dart io中的HttpClient发起的请求,能让我快速接入HTTP网络请求。但HttpClient本身功能较弱,很多常用功能都不支持。我们建议您使用dio 来发起网络请求,它是一个强大易用的dart http请求库,支持Restful API、FormData、拦截器、请求取消、Cookie管理、文件上传/下载,以后会单独介绍dio

  • 发起HTTP请求
  • 处理异步
  • 解码和编码JSON
  • 示例: 解码 HTTPS GET请求的JSON
  • API 文档

1. 导入创建HttpClient对象

http支持位于dart:io,所以使用前, 需要添加一个导入:

import 'dart:io';
var httpClient = new HttpClient();

该 client 支持常用的HTTP操作: such as GET, POST, PUT, DELETE.

配置发起请求

注意,HTTP API 在返回值中使用了Dart Futures。 我们建议使用async/await语法来调用API。
网络调用通常遵循如下步骤:

  1. 创建 client.
  2. 构造 Uri.
  3. 发起请求, 等待请求,同时您也可以配置请求headers、 body。
  4. 关闭请求, 等待响应.
  5. 解码响应的内容.

Get、Post请求示例

页面包涵两个按钮:分别触发_get()、_post() 函数。
Flutter开发之HTTP网络请求:HttpClient(26)_第1张图片
页面代码如下:

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:convert';

_get() async {

  print("_get---");
  var url = 'https://jsonplaceholder.typicode.com/posts/1';
  var httpClient = new HttpClient();

  String result;
  try {
    var request = await httpClient.getUrl(Uri.parse(url));
    var response = await request.close();
    print("statusCode----${response.statusCode}");

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

      print(data.toString());
      print("data----$data");

      result = 'HttpStatus.ok';

    } else {
      result = 'Error getting IP address:\nHttp status ${response.statusCode}';
    }

  } catch (exception) {
    result = 'Failed getting IP address';
  }

  print("result----$result");
}



_post() async {

  print("_post---");
  var httpClient = new HttpClient();

  String result;
  try {
    var url = "http://api.juheapi.com/japi/toh";
    var request = await httpClient.postUrl(Uri.parse(url));

    // 设置请求头
    /*
    request.headers.set("loginSource", "IOS");
    request.headers.set("useVersion", "3.1.0");
    request.headers.set("isEncoded", "1");
    // Content-Type大小写都ok
    request.headers.set('content-type', 'application/json');
    */

    // 添加请求体
    Map jsonMap = {'shopperId': 9356,'machineId':5117,'orderType':2,'orderId':108};

    Map map1 = new Map();
    map1["v"] = "1.0";
    map1["month"] = "7";
    map1["day"] = "25";
    map1["key"] = "bd6e35a2691ae5bb8425c8631e475c2a";

    request.add(utf8.encode(json.encode(map1)));

    HttpClientResponse response = await request.close();
    String responseBody = await response.transform(utf8.decoder).join();
    print("statusCode----${response.statusCode}");

    if (response.statusCode == HttpStatus.ok) {
      print('请求成功');
      print(response.headers);//打印头部信息
      print("post------$responseBody");

      result = 'HttpStatus.ok';

    } else {
      result = 'Error getting IP address:\nHttp status ${response.statusCode}';
    }

  } catch (exception) {
    result = 'Failed getting IP address';
  }

  print("result----$result");
}


class HttpClientTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text('HttpClientTest'),
      ),

      body: Center(
        child:Column(

          children: [

            SizedBox(height: 32.0),

            Text("HttpClient Get Post 练习"),

            SizedBox(height: 32.0),

            RaisedButton(
              onPressed: _get,
              child: new Text('Get 请求'),
            ),


            RaisedButton(
              onPressed: _post,
              child: new Text('Post 请求'),
            ),

          ],

        ),
      ),


    );
  }
}

触发_get()的结果
在这里插入图片描述

触发_post()的结果
Flutter开发之HTTP网络请求:HttpClient(26)_第2张图片
完成了!


特别感谢:
Flutter -------- 网络请求之HttpClient

你可能感兴趣的:(Flutter开发教程)