[Flutter]請求阿里百川的API

weixin_34138377發表於2018-05-04

簡單封裝了一下,請求阿里百川的api。只是做了一個簡單的get請求封裝,要更加優雅可以自己再封裝一下。

可以簡單的學習一下Flutter的網路請求用法。

檔案tb_api.dart程式碼如下:

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

// 阿里百川
const AlibcAppKey = "";
const AlibcAppSecret = "";
const AlibcApiUrl = "http://gw.api.taobao.com/router/rest?";

const BCGoodsListURL = "taobao.tae.items.list";
const BCGoodsDetailURL = "taobao.item.detail.get";

// md5 加密
String generateMd5(String data) {
  var content = new Utf8Encoder().convert(data);
  var digest = md5.convert(content);
  return hex.encode(digest.bytes);
}

// 公共請求引數
Map<String, String> commonParams(String method) {
  const app_key = AlibcAppKey;
  DateTime date = new DateTime.now();

  // yyyy-MM-dd HH:mm:ss
  String timestamp =
      "${date.year.toString()}-${date.month.toString().padLeft(2,'0')}-${date.day.toString().padLeft(2,'0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}";
  const format = "json";
  const v = "2.0";
  const sign_method = "md5";
  const simplify = "true";

  var params = {
    "app_key": app_key,
    "format": format,
    "method": method,
    "sign_method": sign_method,
    "timestamp": timestamp,
    "v": v
  };

  return params;
}

// 這是商品列表介面的引數
Map<String, String> goodsListParams() {
  return {
    "num_iids": '534014773552',
    "fields": "cid,title,nick,price,num,pic_url"
  };
}

// 最終的請求引數 通過公共引數和介面引數確定簽名
Map<String, String> requestParameters(String method, Map<String, String> customParams) {
  var params = commonParams(method);
  var custom = customParams;

  // print("介面引數: \(custom)")
  custom.forEach((k, v) {
    params[k] = v;
  });

  // print("最終引數: \(params)")

  List<String> keys = params.keys.toList();
  keys.sort();

  // print("排序後的引數:\(keys)")
  String total = '';
  keys.forEach((key) {
    total += '${key}${params[key]}';
  });

  String sign =
      generateMd5(AlibcAppSecret + total + AlibcAppSecret).toUpperCase();
  params['sign'] = sign;

  return params;
}

// 讀取商品列表
getGoodsList() {
  get(requestParameters(BCGoodsListURL, goodsListParams()));
}

// 讀取商品詳情
getGoodDetail(String itemId) {
  var params = { "item_id" : itemId, "fields" : "item" };
  get(requestParameters(BCGoodsDetailURL, params));
}

Future<Map> get(Map params) async {
  final uri = new Uri.http('gw.api.taobao.com', '/router/rest', params);
  // print('請求的url: ${uri}');
  final headers = {
    "Content-Type": "application/json",
  };

  final response = await http.get(uri, headers: headers);
  var data = json.decode(response.body);
  print('阿里返回的資料:${data}');

  return data;
}

相關文章