JS和C#(HttpWebRequest)請求天氣api獲取數據

前言

因爲需要做了一個天氣預報的功能,所以在網上找了一些api,發現很多的都要收費或有些請求限制,最後被我找到一個完全免費且沒限制,非常好的天氣api:https://www.tianqiapi.com/api/,使用這個api十分簡單,只需要加上一個cityid參數就可以,詳細文檔可以參考官網:天氣api文檔,https://www.tianqiapi.com/?action=v1


圖片


下面就直接說一下使用實例。

圖片2

JS請求調用

核心請求代碼如下,其實就是一個簡單的ajax請求,然後再將返回數據拼接成html代碼在瀏覽器上顯示,有兩個關鍵點,
一:cityid我這邊是寫死了的,因爲我的需求只是需要在網站上顯示這個地方的天氣,所以其實也是可以動態傳參顯示其他城市的,至於cityid這個值也是可以官網中獲得。
二:就是根據返回的json數據結構獲取自己想要的數據,其他的就是我爲了處理數據寫了兩個處理數據的函數,以及一些頁面樣式,這些詳細代碼我都會在文章最後可以下載。


$.ajax({                url:"https://www.tianqiapi.com/api/?version=v1&cityid=101010100",                type: "post",                //data: cityid,
                dataType: 'json',                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',                success: function (json) {                    //console.log(json);
                    var data = json;                    var t = '<div class="today-box">'
                        + '<div class="city" style="font-size:15px;">北京</div>'
                        + '<div class="date">' + data.data[0].date + data.data[0].week + '</div>'
                        + '<div class="pic"><img width="72px" height="72px;" src=' + getImageName(data.data[0].wea) + ' /> </div>'
                        + '<div class="wd">' + data.data[0].tem2 + "-" + data.data[0].tem1  + '</div>'
                        + '<div class="tq">' + data.data[0].wea + '&nbsp;' + data.data[0].win[0] + '</div>'
                        + '</div>';
                    t = t + '<div class="next-day-box">';                    for (var i = 1; i < data.data.length; i++) {
                        t = t + '<div class="next-day-weather">'
                            + '<div class="zhou">' + data.data[i].week + '</div>'
                            + '<div class="date">' + formatDate(data.data[i].date, 2) + '</div>'
                            + '<div class="pic"><img width="60px" height="60px;" src=' + getImageName(data.data[i].wea) + ' /> </div>'
                            + '<div class="wd">' + data.data[i].tem2 + "-" + data.data[i].tem1  + '</div>'
                            + '<div class="tq">' + data.data[i].wea + '</div>' + '</div>';
                    }
                    t = t + '</div>';
                    $("#day7yb").html(t);
                }

圖片


效果圖

圖片


圖片3

C#請求調用

C#做web請求主要是用.NET封裝好的類HttpWebResponse,HttpWebRequest,這兩個類都是System.Net裏,所以使用前要先using。
在這裏我是先創建一個公共類,裏面寫了兩個GET與POST方法,然後這樣就可以方便調用,貼上部分代碼,

public static string Get(string Url)
        {
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);//創建請求
            request.Proxy = null;//IP代理池
            request.KeepAlive = false;//是否一直保持連接
            request.Method = "GET";//請求方法
            request.ContentType = "application/json; charset=UTF-8";//請求內容返回格式和編碼
            request.AutomaticDecompression = DecompressionMethods.GZip;//允許壓縮內容,可以提高請求效率
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//獲得響應
            Stream myResponseStream = response.GetResponseStream();//將響應內容生成流
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);            string retString = myStreamReader.ReadToEnd();//讀取所有的響應內容並將結果生成字符串
            string r = Regex.Unescape(retString);//將返回的unicode轉化爲中文
            myStreamReader.Close();
            myResponseStream.Close();            if (response != null)
            {
                response.Close();
            }            if (request != null)
            {
                request.Abort();
            }            return r;
        }

題外話,C#就這樣一個GET請求寫了這麼多,真心有點麻煩,在這方面還是python簡單,如果是python做這樣的請求的話也就幾行代碼。

import requests
response = requests.get('https://www.tianqiapi.com/api?version=v1&cityid=101010100')
response.encoding="utf-8"#print(response.text)print (response.json())

迴歸正題,在上述C#請求中,需要注意的點有一個,就是編碼問題,我當時是踩坑了,如果響應的內容是中文亂碼的話,一般就是utf-8編碼問題,得這裏聲明編碼方式,StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
如果返回的中文是unicode,就是類似這種,

圖片


所以就需要將unicode轉換爲中文string r = Regex.Unescape(retString);


題外話:
中文轉UnicodeHttpUtility.UrlEncodeUnicode(string str);
轉換後中文格式:"%uxxxx" 舉例:"柳_abc123" 轉換結果是:"%u67f3_abc123"
Unicode轉中文1HttpUtility.UrlDecode(string str);
str格式:"%uxxxx" ,舉例:"%u67f3_abc123"
Unicode轉中文2Regex.Unescape(string str);
str格式:"sdfasdf\uxxxx" ,舉例:"sdfasdf(\uxxxx對應的中文)"





最後就是調用代碼,因爲我是用mvc寫的,這裏是在控制器裏調用那個請求類,然後返回json字符串,這裏也有一個點需要注意,就是返回的response會有很多\轉義字符,這些是C#自動添加的,可以不用處理,直接返回後,轉義字符就不存在。

public ActionResult WeatherForJson()
        {            string response= HttpWebResponseUtility.Get("https://www.tianqiapi.com/api?version=v1&cityid=101010100");            //此時response的字符串有很多\,這是C#自動轉義的,不用處理
            //string s = response.Replace(@"\","");
            //JObject jb = (JObject)JsonConvert.DeserializeObject(response);
           // string city = jb["cityid"].ToString();//這裏是嘗試使用json的序列化效果
            //return Json(jb, JsonRequestBehavior.AllowGet);
            return Content(response);//頁面返回json字符串
            //return View();
        }

返回結果:

圖片


至於post請求其實跟get請求都差不多,就是多了請求參數的處理而已,這裏就不贅述了,在代碼那裏我也是做了post請求的事例,如果有興趣的話可以下載源碼看。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章