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);
        }

 

posted @ 2018-04-16 12:21  吃辣椒的小毛驴  阅读(1934)  评论(0编辑  收藏  举报