ASP.NET MVC在控制器分別中用Get和POST模式調用天氣url返回數據亂碼
!!!已解決,分享分享!!!
感謝大神:Daniel Cai
感謝大神:顧曉北
post方法,本人不知道,如果有大神知道,請指導!!
//用UTF-8轉碼有漢字參數的url protected string UrlUtf_8(string url) { byte[] bs = Encoding.GetEncoding("UTF-8").GetBytes(url); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bs.Length; i++) { if (bs[i] < 128) sb.Append((char)bs[i]); else { sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0')); sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0')); } } return sb.ToString(); } //用UrlGB2312轉碼有漢字參數的url protected string UrlGB2312(string url) { byte[] bs = Encoding.GetEncoding("GB2312").GetBytes(url); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bs.Length; i++) { if (bs[i] < 128) sb.Append((char)bs[i]); else { sb.Append("%" + bs[i++].ToString("x").PadLeft(2, '0')); sb.Append("%" + bs[i].ToString("x").PadLeft(2, '0')); } } return sb.ToString(); } //get方法 這裡url的模擬地址為http://wthrcdn.etouch.cn/weather_mini?city=北京 public string GetFunction(string url) { string serviceAddress = url; //HttpWebRequest類繼承於WebRequest,並沒有自己的構造函數,需通過WebRequest的Creat方法 建立,並進行強制的類型轉換 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = "text/html;charset=UTF-8"; request.Method = "GET"; //通過HttpWebRequest的GetResponse()方法建立HttpWebResponse,強制類型轉換 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //GetResponseStream()方法獲取HTTP響應的數據流,並嘗試取得URL中所指定的網頁內容 Stream myResponseStream = response.GetResponseStream(); //站點在響應的時候用gzip壓縮過了,用using (var gStream = new GZipStream(myResponseStream, CompressionMode.Decompress)){}解壓 using (var gStream = new GZipStream(myResponseStream, CompressionMode.Decompress)) { //Encoding.GetEncoding("UTF-8")轉碼 StreamReader myStreamReader = new StreamReader(gStream, Encoding.GetEncoding("UTF-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); response.Close(); myResponseStream.Close(); return retString; } }View Code