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

时间:2020-04-19 10:51:46   收藏:0   阅读:98

在发送微信客服消息初始使用的是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;
            }
        }
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!