Flutter系列之Dart网络编程

dart:io中有Http请求的内容
这里再记录一下http这个包的简单用法

pubspec.yaml

name: Note20
dependencies:
  http: any

main.dart

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

main() async {
  /**
   * 向目标主机发送一次get请求
   * 自动创建临时Client,请求结束后自动删除
   * 如果要对主机发送多个请求,要手动new Client
   *
   * var client = new Client();
   * client.get(...)
   * client.put(...)
   *
   * 其他请求有:post put patch delete
   * 返回值为Future<Response>
   *
   * Http请求有可能返回Response,或者异常
   */
  String url = "http://www.cndartlang.com";
  Http.Response response = await Http.get(url);

  /**
   * 获取标签头字段的名称,并遍历输出
   * 获取标签头某个字段的值
   */
  response.headers.keys.forEach((str) => print(str));
  print("content-type = ${response.headers['content-type']}\n");

  /**
   * 获取响应对象的主体内容
   * Response.bodyBytes返回字节List
   *
   * Response.body返回String
   * 但仍然是通过对bodyBytes进行编码来实现
   * 调用Response.body的时候,默认以content-type的字段值来进行编码
   * 比如content-type = text/html; charset=utf-8,则采用UTF8进行编码
   *
   * 如果源码有无效的字符
   * 那么直接调用Response.body的时候出错,会显示错误:
   * FormatException: Bad UTF-8 encoding 0xfd
   * 那么我们就需要手动对字节进行编码
   * 设置allowMalformed为true,对无效或未完成的字符进行替换
   */
  List<int> bytes = response.bodyBytes;
  String utf8Body = UTF8.decode(bytes, allowMalformed: true).substring(0, 800);
  print(utf8Body + "\n");

  /**
   * read和readBytes作用为向主机发送get请求,但不返回Response
   * 返回值为Future<String>和Future<Uint8List>
   */
  print((await Http.read("http://www.baidu.com")).substring(0, 800) + "\n");

  /**
   * 设置请求的标签头
   * 通过修改User-Agent来模拟iPhone 6请求
   * 显示手机版百度首页
   *
   * 可以对比之前read的字符串
   */
  Http.get('http://www.baidu.com',
      headers: {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'}).then((resp) {
    print(resp.body.substring(0, 800));
  });

}

运行结果:

connection
x-powered-by
set-cookie
date
vary
content-encoding
content-length
content-type
server
content-type = text/html; charset=utf-8

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dart语言中文社区-中国最大的Dart语言编程学习交流社区</title>

<meta name="keywords" content="Dart,Dart教程,Dart下载,Dart源码,Dart论坛,Dart社区,Flutter,Flutter教程" />
<meta name="description" content="DartLang中文社区,专注于Dart技术研究、开发、教程、源码资源等,我们的目标是打造一个优秀的Dart中文交流社区。 " />
<meta name="generator" content="Discuz! X3.2" />
<meta name="author" content="Discuz! Team and Comsenz UI Team" />
<meta name="copyright" content="2001-2013 Comsenz Inc." />
<meta name="MSSmartTagsPreventParsing" content="True" />
<meta http-equiv="MSThemeCompatible" content="Yes" />
<base href="http:/

<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="百度搜索" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-pre

<!DOCTYPE html>
<html><!--STATUS OK--><head><meta name="referrer" content="always" /><meta charset='utf-8' /><meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><link rel="apple-touch-icon-precomposed" href="//m.baidu.com/static/index/screen_icon.png"/><meta name="format-detection" content="telephone=no"/><noscript><style type="text/css">#page{display:none;}</style><meta http-equiv="refresh" content="0; URL=http://m.baidu.com/?from=1014571x&grade=hk&pu=sz%401321_480&t_noscript=jump" /></noscript><title>百度一下</title><style type="text/css" id='spa-base-style'>#search-card {display: none;}</style><style type="text/css" class="spa-index-style" data-lsid="plus_css_head">body,h1,h2,h3,p,div,ol,ul,input,button{margin:0;padding:0}body

本文图片资料来源出自“Dart语言中文社区”,允许转载,转载时请务必以超链接形式标明文章原始出处   

猜你喜欢

转载自blog.csdn.net/s1120080286/article/details/83446083