如何用Dart调用RESTful Web Service

几个月前Google发布了一个新的操作系统Fuchsia。Dart是这个新操作系统的主要编程语言。最近发现Google的移动开发框架Flutter也使用Dart,于是就想看下。

开发环境

安装Dart SDK。

安装IDE IntelliJ IDEA。Community版本免费。运行IDE,通过File > Settings > Plugins安装Dart插件:

调用RESTful Web Service

创建一个命令行工程:

如何用Dart调用RESTful Web Service_第1张图片

添加需要的库:

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

dart:打头的是内置的库,package:打头的需要通过pub来下载。pub是一个像npm一样的包管理工具。在Dart SDK中自带。

打开pubspec.yaml添加依赖库:

name: barcode
version: 0.0.1
description: A simple console application.
dependencies:
  http:

这个时候需要用pub下载相应的库。

读取一个条形码图像文件:

var bytes = await new File(filename).readAsBytes();

把byte转换成base64:

import 'dart:convert';
String base64 = BASE64.encode(bytes);

构建一个JSON数据:

String jsonData = '{"image":"$base64","barcodeFormat":234882047,"maxNumPerPage":1}';

调用Dynamsoft barcode web service来获取解码结果:

var response = await http.post(url, headers: {'Content-Type': 'application/json'}, body: jsonData);
print("Response status: ${response.statusCode}");
print(response.headers);
if (response.statusCode != 200) {
  print("Server Error !!!");
  return;
}
print("Response body: ${response.body}");
 
// https://api.dartlang.org/stable/1.21.0/dart-convert/JSON-constant.html
Map result = JSON.decode(response.body);
print("Barcode result: " + result['barcodes'][0]['displayValue']);

截图:

如何用Dart调用RESTful Web Service_第2张图片

源码

https://github.com/yushulx/dartlang-barcode-webservice

你可能感兴趣的:(如何用Dart调用RESTful Web Service)