wp8.1 调用智慧天气SmartWeatherAPI

在调用api应用的过程,我们需要用hmac加密技术,它是一种基于hash的加密算法,通过一个双方共同约定的密钥,在发送message前,对密钥进行了sha散列计算,在生成消息又对此密钥进行了二次加密,通过周期性的更换密钥,安全性可以得到保障。

在wp8.1 sdk中很多传统系统类库被整编进以windows打头的命名空间中,很多刚接触wp8.1朋友可能觉得疑惑。

代码所需命名空间。

1 using System;
2 using System.Net.Http;
3 using System.Threading.Tasks;
4 using Windows.Security.Cryptography;
5 using Windows.Security.Cryptography.Core;
6 using Windows.Storage.Streams;

 加密方法。

 1 public string CreateHMAC(string publicKey, string privateKey)
 2 {
 3     string strAlgName = MacAlgorithmNames.HmacSha1;
 4     MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName);
 5 
 6     IBuffer data = CryptographicBuffer.ConvertStringToBinary(publicKey, BinaryStringEncoding.Utf8);
 7     IBuffer buffKeyMaterial = CryptographicBuffer.ConvertStringToBinary(privateKey, BinaryStringEncoding.Utf8);
 8     CryptographicKey hmacKey = objMacProv.CreateKey(buffKeyMaterial);
 9 
10     var buffHMAC = CryptographicEngine.Sign(hmacKey, data);
11 
12     return CryptographicBuffer.EncodeToBase64String(buffHMAC);
13 }

 调用方式,根据天气网api得知,加密的message为除去key之外的url,再根据私钥签名加密,得到最终的key。

 1 public MainPageViewModel()
 2 {
 3  GetAsync();  4 }  5  6 public async void GetAsync()  7 {  8 string areaId = "101010100";  9 string type = "observe"; 10 string date = System.DateTime.Now.ToString("yyyyMMddHHmm"); 11 string appId = "---天气网提供的appid---"; 12 string privateKey = "---天气网提供的key---"; 13 string publicKey = string.Format("http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}", 14  areaId, type, date, appId); 15 16 string key = CreateHMAC(publicKey, privateKey); 17 string url = string.Format(@"http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}&key={4}", 18 areaId, type, date, appId.Substring(0, 6), key); 19 20 var httpClient = new HttpClient(); 21 var content = await httpClient.GetStringAsync(url); 22 await Task.Run(() => 23  { 24 string c = content; 25  }); 26 }

返回的结果就是一串json了。

转载于:https://www.cnblogs.com/yuefei/p/3862544.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值