C# 簡單POST請求 同時防止中文亂碼的出現

實現POST網絡請求方法網絡

public static string HttpPost(string url,string postDataStr)
{
            string strReturn;
            //在轉換字節時指定編碼格式
            byte[] byteData = Encoding.UTF8.GetBytes(postDataStr);  

            //配置Http協議頭
            HttpWebRequest resquest= (HttpWebRequest)WebRequest.Create(url);
            resquest.Method = "POST";
            resquest.ContentType = "application/x-www-form-urlencoded";
            resquest.ContentLength = byteData.Length;

            //發送數據
            using (Stream resquestStream = resquest.GetRequestStream())
            {
                resquestStream.Write(byteData, 0, byteData.Length);
            }

            //接受並解析信息
            using (WebResponse response = resquest.GetResponse())
            {
                //解決亂碼:utf-8 + streamreader.readToEnd
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                strReturn = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
            }

            return strReturn;
}
相關文章
相關標籤/搜索