c# 調取墨跡調用墨跡天氣接口保存到數據庫


一、墨跡接口調用


        private String host =ConfigurationManager.AppSettings["WeatherHost"];//接口直接寫到webconfig中
        private const String pathWeather = "/whapi/json/alicityweather/briefforecast3days";
        private const String method = "POST";
        private String appcode = ConfigurationManager.AppSettings["WeatherAppCode"];//你的appcode,
        private const String pathAQI = "/whapi/json/alicityweather/briefaqi";
        private string GetWeatherORAQI(string path, int cityId = 2)
        {
            String querys = "";
            String bodys = "cityId=" + cityId;
            String url = host + path;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (host.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根據API的要求,定義相對應的Content-Type
            httpRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            //Console.WriteLine(httpResponse.StatusCode);
            //Console.WriteLine(httpResponse.Method);
            //Console.WriteLine(httpResponse.Headers);
            Stream st = httpResponse.GetResponseStream();
            StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
            return reader.ReadToEnd();
        }

        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

二、這里接口調用可以直接在墨跡實例中找到,返回數據格式為JSON格式,下面進行返回天氣數據處理。

                var json = GetWeatherORAQI(pathWeather); //接口調用,返回JSON數據var WeatherJson = JsonConvert.DeserializeObject<WeatherJson>(json);//數據反序列化
                List<WeatherModel> models = new List<WeatherModel>();
//循環獲取未來三天天氣,保存到集合中
foreach (var item in WeatherJson.data.forecast) { WeatherModel mode = new WeatherModel(); mode.city = WeatherJson.data.city.pname; mode.date = item.predictDate; mode.weather = item.conditionDay; mode.temperature = string.Format("{0}-{1}", item.tempDay, item.tempNight); mode.wind = Enum.GetName(typeof(WindEnum), Convert.ToInt32(item.windLevelDay.Split('-')[0])); mode.airQuality = GetAQI(int.Parse(AQIModel.data.aqi.value)); mode.dress = item.windLevelDay.Split('-')[0]; mode.curtemperature = item.tempDay; models.Add(mode); }
//未來三天天氣,進行序列化保存到數據庫中
var weather = JsonConvert.SerializeObject(models); WeatherInfo winfo = new WeatherInfo() { Date = DateTime.Now.Date, CityCode = 2, Weather = weather }; _context.WeatherInfo.Add(winfo); _context.SaveChanges();

三、天氣需要每天獲取最新,這里可用定時任務完成,每天早晨8點進行更新

        public MyJobs()
        {
            Schedule(() =>
            {
                IServices.IWeatherService _service = new WeatherService();
                _service.Save();
            }).ToRunEvery(1).Days().At(8, 0);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM