且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Dart的HTTP请求和响应(2)

更新时间:2022-09-16 21:31:30

向服务器发多个请求

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

//输出响应正文
printResponseBody(response) {
  //输出响应正文的长度
  print(response.body.length);
  //控制输出的长度在100以内
  if (response.body.length > 100) {
    print(response.body.substring(0, 100));
  } else {
    print(response.body);
  }
  print('...\n');
}

main(List<String> arguments) {
  var url = 'http://www.google.com/';
  //Client类,保持持久连接,向同一个服务器发多个请求
  var client = new http.Client();
  //第一次请求/search
  client.get('${url}/search').then((response) {
    printResponseBody(response);
    //第二次请求/doodles
    return client.get('${url}/doodles');
  })
  .then(printResponseBody)
  //完成后关闭Client连接
  .whenComplete(client.close);
}

代码大概意思是,与服务器保持连接的情况下发两次不同的请求,效果如下
Dart的HTTP请求和响应(2)

处理请求错误

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

//访问正确时的操作
handleSuccess(http.Response response) {
  print('成功访问了网站!');
  print(response.body);
}

//访问错误时的操作
handleFailure(error) {
  print('发生了一些错误!');
  print(error.message);
}

main(List<String> arguments) {
  http.get("http://some_bogus_website.org")
    ..then(handleSuccess)
    ..catchError(handleFailure);
}

因为代码中的请求地址是无效的,所以一定会出错,然后输出指定的错误信息
Dart的HTTP请求和响应(2)

获取重定向的记录

import "dart:io" show HttpClient, RedirectInfo;

main(List<String> arguments) {
  var client = new HttpClient();
  //使用GET方法打开一个HTTP连接
  client.getUrl(Uri.parse('http://google.com'))
    .then((request) => request.close())
    .then((response) {
      //获得所有重定向的列表
      List<RedirectInfo> redirects = response.redirects;
      //循环输出重定向的记录
      redirects.forEach((redirect) {
        print(redirect.location);
      });
    });
}

访问代码中的地址时只重定向过一次,所以只有一条记录
Dart的HTTP请求和响应(2)

获取响应正文的字符串

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

main(List<String> arguments) {
  http.read("http://www.google.com/").then(print);
}

这个简单得不行,直接看一下效果吧
Dart的HTTP请求和响应(2)

获取响应正文的二进制

这个要用到crypto包,还是先把分享放出来http://pan.baidu.com/s/1dDARcrB

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

main(List<String> arguments) {
  var url = "https://www.dartlang.org/logos/dart-logo.png";
  http.get(url).then((response) {
    //将响应内容转换成字节列表
    List<int> bytes = response.bodyBytes;
    //将字节列表转换成Base64编码的字符串
    String base64 = CryptoUtils.bytesToBase64(bytes);
    print(base64);
  });
}

因为Base64编码的字符串太长了,我就复制在记事本上了
Dart的HTTP请求和响应(2)

获取响应的头文件

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

main(List<String> arguments) {
  var url = 'http://httpbin.org/';
  http.get(url).then((response) {
    //获取头文件的映射
    print(response.headers.keys);
    //获取头文件的信息
    print("access-control-allow-origin = ${response.headers['access-control-allow-origin']}");
    print("content-type = ${response.headers['content-type']}");
    print("date = ${response.headers['date']}");
    print("content-length = ${response.headers['content-length']}");
    print("connection = ${response.headers['connection']}");
  });
}

执行代码后的效果如下
Dart的HTTP请求和响应(2)