[Flutter]请求阿里百川的API

简单封装了一下,请求阿里百川的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;
}
    原文作者:Brant白叔
    原文地址: https://www.jianshu.com/p/b1d6d8a210da
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞