首页 > 代码库 > ASP.NET MVC在控制器中分别用Get和post模式调用天气url返回数据乱码

ASP.NET MVC在控制器中分别用Get和post模式调用天气url返回数据乱码

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

 

ASP.NET MVC在控制器中分别用Get和post模式调用天气url返回数据乱码