博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c# 调取墨迹调用墨迹天气接口保存到数据库
阅读量:6037 次
发布时间:2019-06-20

本文共 4256 字,大约阅读时间需要 14 分钟。

一、墨迹接口调用

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
(json);//数据反序列化 List
models = new List
(); //循环获取未来三天天气,保存到集合中 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);        }

 

转载于:https://www.cnblogs.com/xinbaba/p/8855263.html

你可能感兴趣的文章
WindowsServer 2008 AD搭建FTP隔离用户
查看>>
lmdb
查看>>
大文件如何传输,大文件的传输方式有哪些?
查看>>
docker的持久化存储和共享存储和网络架构
查看>>
撕掉普通程序员的标签,这才是真正的大数据工程师!
查看>>
Windows下安装Sqlmap过程及遇到的问题
查看>>
BSD常见分支
查看>>
开挂了!这5个Word技巧真的是超级实用,值得收藏!
查看>>
三分钟了解实时流式大数据分析
查看>>
留与后人一段面试的总结
查看>>
Spring基于XML方式配置事务
查看>>
T-MBA学习营 | 寒窗十数载,我们原来并不会学习?
查看>>
log4j.properties模板
查看>>
Linux:信号(上)
查看>>
vmware虚拟化无法迁移虚拟机
查看>>
SQL UPDATE实现多表更新
查看>>
最近有个需求,就是把某个网址跳转到另外一个网址
查看>>
innobackupex 在增量的基础上增量备份
查看>>
Windows Server 2012 R2 DirectAccess功能测试(2)App1服务器安装及配置
查看>>
基于清单的启动器的实现
查看>>