【MVC__微信客服消息】发送微信客户消息 invalid openid hint 及 中文乱码

在发送微信客服消息初始使用的是HttpWebRequest,

设置request.ContentType = "application/x-www-form-urlencoded";

或者是 request.ContentType = "application/json; encoding=utf-8";

都报invalid openid hint错误

后来发现 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.ASCII);

是StreamWriter未使用Encoding.ASCII,改正后但是发送的消息还是中文乱码,这就很蛋疼了

        public static string PostWeiXin(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            //request.ContentType = "application/json; encoding=utf-8";
            request.ContentType = "application/x-www-form-urlencoded";
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.ASCII);
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            //response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

鄙人才疏学浅,经过不断的肝,发现一个好用的类,使用WebClient完美解决 invalid openid hint 报错以及中文乱码问题

所有说,还是少用HttpWebRequest吧

        public static string SendMsgWechat(string url, string content)
        {
            using (WebClient webClient = new WebClient())
            {
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                string sResponse = webClient.UploadString(url, "POST", content);
                return sResponse;
            }
        }
上一篇:C# 代码实现 Windows服务:计时器=>简单实现


下一篇:VS2015+Windows服务简易教程