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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM