Dart的HTTP请求和响应(1)

GET请求

在上代码之前,先把所需要的http包分享出来http://pan.baidu.com/s/1jGH2zgq

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

main(List<String> arguments) {
  var url = 'http://httpbin.org/';
  //向指定URL发送GET请求
  http.get(url).then((response) {
    print("响应状态: ${response.statusCode}");
    print("响应正文: ${response.body}");
  });
}

代码很简单,效果如下

POST请求

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

main(List<String> arguments) {
  var url = 'http://httpbin.org/post';
  //向指定URL发送带参数的POST请求
  http.post(url ,body: 'name=doodle&color=blue').then((response) {
    print("响应状态: ${response.statusCode}");
    print("响应正文: ${response.body}");
  });
}

这也很简单,效果如下

展示JSON数据

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

main(List<String> arguments) {
  var url = 'https://api.github.com/users/dart-lang/repos';
  http.get(url ,headers : {'User-Agent':'Dart/1.0(My Dart client)'}).then((response) {
    //解析响应字符串,并生成Json对象
    List<String> repos = JSON.decode(response.body);
    //输出说明字符串
    var heading = 'Repository | Star count | Fork count';
    print(heading);
    //输出与说明字符串等长的‘=’字符串
    print(new List.filled(heading.length, '=').join());
    //循环输出Json对象的指定参数
    for (var repo in repos) {
      print(
          "${repo['name']} | "
          "${repo['stargazers_count']} | "
          "${repo['forks_count']}");
    }
  });
}

先来看看里面的JSON字符串
Dart的HTTP请求和响应(1)_第1张图片
晕了没,再看看代码执行后展示的部分JSON数据
Dart的HTTP请求和响应(1)_第2张图片
这样就好看多了

你可能感兴趣的:(http,请求,arguments,响应,Dart)