zoukankan      html  css  js  c++  java
  • 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了。

  • 相关阅读:
    AngularJS-webapp($q)
    mybatis
    maven联通网络下中央仓库不能访问的解决办法
    IDEA闪退问题
    scala学习笔记(8)文件和正则表达式
    scala学习笔记(8)
    scala学习笔记(7)
    kafka复习(2)
    第一天
    while循环
  • 原文地址:https://www.cnblogs.com/yuefei/p/3862544.html
Copyright © 2011-2022 走看看