幾行c#代碼,輕鬆搞定一個女大學生

幾行c#代碼,輕鬆搞定一個女大學生

的做業。。。html

哈哈,標題黨了哈,可是是真的,在外面敲代碼,想賺點外快,接到了一個學生的期末考試,是一個天氣預報的程序。程序並不難。json

看到這個需求第一個想法就是隻要找到合適天氣預報接口一切都是小意思,說幹就幹,立馬跟學生溝通價格。c#


不過談報價的過程當中,差點沒讓我一口老血噴鍵盤上,話說咱們程序猿的人工何時這麼低廉了。。。oh my godapi


​50十塊,你跟我開什麼國際玩笑!!不夠意外驚喜仍是有的,竟然是個妹子嘿嘿,哎呀什麼錢不錢的多傷感情。微信

老哥送你一套代碼,小妹妹之後你好好學習,不懂得問老哥,而後順利的家了微信(妹子很漂亮)。app


廢話很少說開幹,這個程序最大的難點就是找一個合適的天氣預報接口,之前沒有作過相似的程序,致使70%時間浪費在找接口以及調試接口上,不過也算我運氣好,找到了一個免費接口,接口的技術兄弟人也超棒,大大的贊。post

在這裏分享給你們 https://www.tianqiapi.com/?action=doc(剛兩天界面就改版了,差點覺得我訪問錯了)。學習

做爲一個免費的接口,數據詳細到這種程度,大大的良心,應付一個大學生的期末做業,簡直大材小用。jsonp

 


找接口後,立馬開始寫代碼,因爲女學生要的緊,哦,不催得緊,因此代碼一切從簡,只保留核心功能,錦上添花的東西一概不要,首先搞定http請求類。url

    public class HttpHelper
    {
        /// <summary>
        /// 發送請求的方法
        /// </summary>
        /// <param name="Url">地址</param>
        /// <param name="postDataStr">數據</param>
        /// <returns></returns>
        private string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream,         
            Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

    }

 

http請求搞定,接下來獲取全部的城市,主要爲了效驗用戶的輸入,不可能你輸入什麼我都去查天氣,就算你是女學生也不行,你們夥說對不?

https://cdn.huyahaha.com/tianqiapi/city.json 全國全部城市接口。

https://www.tianqiapi.com/api/ 天氣接口,下爲參數列表。

參數 名稱 備註
version 版本標識 必填字段 目前可用值: v1
callback jsonp參數 如: jQuery.Callbacks
如下參數三選一
cityid 城市編號 如: 101120201
city 城市名稱 如: 海淀,青島,大連 (不要帶市和區)
ip IP地址 此IP地區的天氣

你們能夠自行查看下接口的返回值,簡直詳細到喪心病狂。

添加幾個model類用來序列化json

    public class City
    {
        public string cityZh { get; set; }
        public string id { get; set; }
    }
    public class Data
    {
        public string day { get; set; }
        public string date { get; set; }
        public string week { get; set; }
        public string wea { get; set; }
        public string air { get; set; }
        public string air_level { get; set; }
        public string air_tips { get; set; }

        public string tem { get; set; }
        public string tem1 { get; set; }
        public string tem2 { get; set; }

        public string win_speed { get; set; }
    }
    public class Weather
    {
        public string cityid { get; set; }
        public string update_time { get; set; }
        public string city { get; set; }

        public List<Data> data { get; set; }
    }

 

準備工做完成,開始調用接口,因爲只有兩個接口,接口文檔又很清楚,對方技術兄弟也很給力。沒費什麼勁接口調試成功,因而寫了下面兩個方法。

    public class Weather
    {
        HttpHelper http = new HttpHelper();
        List<City> citys = new List<City>();

        public model.Weather GetWeather(string name)
        {
            if (!citys.Any(a => a.cityZh == name.Trim()))
            {
                throw new KeyNotFoundException("未找到相關城市,請您檢查城市名");
            }
            var data = http.HttpGet($"https://www.tianqiapi.com/api/?version=v1&city={name}", "").TrimStart('(');
            return JsonConvert.DeserializeObject<model.Weather>(data);
        }

        public void GetCity()
        {
            var data = http.HttpGet("  https://cdn.huyahaha.com/tianqiapi/city.json", "");
            citys = JsonConvert.DeserializeObject<List<City>>(data);
        }
    }

 

而後就是界面設計,爲了省時間沒有使用更強大的wpf,而使用更簡單快捷的winform5分鐘界面擼完。

爲了方便連控件名都沒有改(若是在公司這麼作,codereview必定會被罵)label3顯示當前城市,6個groupbox爲6天的天氣,一個查詢一個退出,界面搞定。


而後編寫按鈕事件,綁定數據,沒什麼難度。

    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            AllCity();
        }
        Weather weather = new Weather();

        private void Form1_Load(object sender, EventArgs e)
        {
            BindData(city_name.Text.Trim());
        }

        private void AllCity()
        {
            weather.GetCity();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void select_Click(object sender, EventArgs e)
        {

            BindData(city_name.Text.Trim());
        }

        private void BindData(string city)
        {
            model.Weather w = null;
            try
            {
                w = weather.GetWeather(city);
            }
            catch (KeyNotFoundException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception)
            {
                MessageBox.Show("查詢失敗請重試");
            }
            if (w != null)
            {
                SetView(w);
            }
        }
        private void SetCurrentCity(string city)
        {
            label3.Text = city;
        }
        private void SetView(model.Weather model)
        {
            SetCurrentCity(model.city);
            SetLable(model.data);
            SetGroupBox(model.data);
        }

        private void SetLable(List<Data> model)
        {
            var d = model[0];
            label2.Text = WeaderString(model[0]);
            label4.Text = WeaderString(model[1]); ;
            label5.Text = WeaderString(model[2]); ;
            label6.Text = WeaderString(model[3]); ;
            label7.Text = WeaderString(model[4]); ;
            label8.Text = WeaderString(model[5]); ;
        }
        private string WeaderString(Data d)
        {
            string txt = $"日期:{d.date}\r\n天氣:{d.wea}\r\n當前溫度:{d.tem}\r\n溫度:{d.tem1} - {d.tem2}\r\n空氣質量:{d.air_level}\r\n空氣指數:{d.air}\r\n風力:{d.win_speed}";
            return txt;
        }
        private void SetGroupBox(List<Data> model)
        {
            groupBox1.Text = model[0].week;
            groupBox2.Text = model[1].week;
            groupBox3.Text = model[2].week;
            groupBox4.Text = model[3].week;
            groupBox5.Text = model[4].week;
            groupBox6.Text = model[5].week;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

 

搞定了,來看下運行效果,界面雖然簡單但是功能完美實現。


 

代碼下載 https://pan.baidu.com/s/1jOX52_w3VEgGBEPkLbOXXw

相關文章
相關標籤/搜索