Reputation: 73
I want to get a web API.
The web request using HMAC-SHA1 encoding.Just like below:
Following is my code:
getData(){
String APPID = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF";
String APPKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
final String time = readTimestamp(DateTime.now().millisecondsSinceEpoch);
final signDate = "x-date: $time";
var key = utf8.encode(APPKey);
var hmacSha1 = new Hmac(sha1, key);
var hmac = hmacSha1.convert(utf8.encode(signDate));
var base64HmacString = Base64Encoder().convert(hmac.bytes);
var bytes = utf8.encode(""""hmac username=$APPID, algorithm="hmac-sha1", headers="x-date", signature=$base64HmacString""");
var digest = hmacSha1.convert(bytes);
visitAPI(time, '$digest');
}
String readTimestamp(int timestamp){
var format = new DateFormat("EEE, dd MMM yyyy HH:mm:ss");
var time = format.format(DateTime.now().toUtc()) + " GMT";
print(time.toString());
return time.toString();
}
Future<void> visitAPI(String xdate, String authorization) async {
final url = "https://ptx.transportdata.tw/MOTC/v2/Bus/RealTimeByFrequency/Streaming/City/Hsinchu?\$top=30&\$format=JSON";
final response = await http.get(url,
headers: {"x-date": xdate, "Authorization": authorization});
final jsonSt = json.decode(response.body);
print(response.body);
}
I have tried many time but I still got the message:"HMAC signature cannot be verified". Is there any problem on my code? Please help me. Thanks.
Upvotes: 0
Views: 1117