C#调用免费的天气预报接口示例代码

挺好用的接口, 没有调用次数、频率和IP限制, 对接很简单

参数说明
version (版本号, v1代表7天, v6代表1天)
cityid (城市编号)
city (城市名称如:青岛)
ip (ip地址, 默认当前ip天气)

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace ApiSnippet
{
    class Program
    {
        static string GetSignature(string parameters, string secret)
        {
            string[] unsorted = parameters.Split('&');
            List<string> sorted = new List<string>();
            string sortedParams = "";

            //Removing unwanted parameters
            for (int i = 0; i < unsorted.Length; i++) {
                if (!unsorted[i].Contains('=')) {
                    continue;
                }
                string[] keyVal = unsorted[i].Split('=');
                if (keyVal[0].Equals("sign") || keyVal[1].Length == 0) {
                    continue;
                }

                sorted.Add(unsorted[i]);
            }

            if (sorted.Count == 0) {
                return null;
            }

            //Sorting the remaining parameters
            sorted.Sort();

            //Building the sorted parameters string
            for (int i = 0; i < sorted.Count; i++) {
                if(i < sorted.Count-1) {
                    sorted[i] += '&';
                }
                sortedParams += sorted[i];
            }

            sortedParams += secret;

            //Encoding
            byte[] encodedPassword = new UTF8Encoding().GetBytes(sortedParams);
            byte[] hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
            string encoded = BitConverter.ToString(hash).Replace("-", String.Empty).ToLower();

            return encoded;
        }

        static void Main(string[] args)
        {
            //version (版本号, v1代表7天, v6代表1天) 接口参数 cityid (城市编号), city (城市名称如:青岛), ip (ip地址, 默认当前ip天气)
            string parameters = "version=v1";
            string url = String.Concat("https://www.tianqiapi.com/api/?", parameters);
           
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Timeout = 5000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string jsonString;
            using (Stream stream = response.GetResponseStream())   
            {
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                jsonString = reader.ReadToEnd();
            }

            //Response
            Console.WriteLine(jsonString);   
        }
    }
}
发布了43 篇原创文章 · 获赞 38 · 访问量 12万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览