C# 接入 SmartWeatherAPI

2015-09-11  本文已影响270人  过桥

实现效果

1.填写发送申请信息
API地址:http://smart.weather.com.cn/wzfw/smart/weatherapi.shtml

2.等待通过审核,审核周期一至三周
回复邮件如下:


回复邮件回复邮件

3.根据官方文档、以及前辈代码,编写调用示例

代码示例

public string GetKey(string appid, string privateKey, string areaId, string date, string type)
    {
        //使用SHA1的HMAC
        HMAC hmac = HMACSHA1.Create();
        var publicKey = "http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}";
        var data = System.Text.Encoding.UTF8.GetBytes(string.Format(publicKey, areaId, type, date, appid));
        //密钥
        var key = System.Text.Encoding.UTF8.GetBytes(privateKey);
        hmac.Key = key;
        //对数据进行签名
        var signedData = hmac.ComputeHash(data);
        string encodeKey = Server.UrlEncode(Convert.ToBase64String(signedData));
        return string.Format(publicKey, areaId, type, date, appid.Substring(0, 6)) + "&key=" + encodeKey;
    }

    public string GetWeather(string url)
    {
        string strBuff = "";
        char[] cbuffer = new char[256];
        int byteRead = 0;

        Uri httpURL = new Uri(url);
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);

        HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
        Stream respStream = httpResp.GetResponseStream();
        StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
        byteRead = respStreamReader.Read(cbuffer, 0, 256);
        while (byteRead != 0)
        {
            string strResp = new string(cbuffer, 0, byteRead);
            strBuff = strBuff + strResp;
            byteRead = respStreamReader.Read(cbuffer, 0, 256);
        }

        respStream.Close();
        return strBuff;
}

    protected void Page_Load(object sender, EventArgs e)
    {
        
        string appid = "*******";
        string private_key = "****************";
        string address = "101010100";
        string type = "forecast3d";     //type:数据类型(实况:observe,指数:index,常规预告:forecast3d)。
        string url = GetKey(appid, private_key, address, DateTime.Now.ToString("yyyyMMddHHmm"), type);
        strWeather = GetWeather(url);

    }

注意事项

1、官方API地址变更,之前的地址请求无法返回数据请求
错误地址

http:// webapi.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}

正确地址

http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}

2、Type参数不正确

type:数据类型(实况:observe,指数:index,常规预告:forecast3d)

3、参数截取不正确

http://open.weather.com.cn/data/?areaid={0}&type={1}&date={2}&appid={3}&key={4}
areaid为行政区划代码(见邮件附件)
type类型分实况:observe,指数:index,常规预告:forecast3d
date为请求时间,格式为yyyyMMddHHmm
appid为 Appid前6位字符(邮件中提供Appid)
key通过Appid,privateKey加密计算(邮件中提供Appid,privateKey)

参考资料

薛定谔の喵
Jolan

上一篇下一篇

猜你喜欢

热点阅读