winform 客户端 HTTP协议与服务端通信以及解决中文乱码
本来从来没有仔细研究过Http协议,今天因为公司业务需求,调试了半天,终于现在会Winform用Http协议与服务端通信了,其中常用的有POST和Get方式;
仔细看了人人网和新浪等大部分都是采用GET方式获取数据的,MSN截图如下:
还是不要脱离本文的主要目的:
模拟实现登录代码如下:
1 private void pictureBox3_Click(object sender, EventArgs e) 2 { 3 string strUserName = textEdit1.Text.Trim(); //用户名 4 string strUserPwd = textEdit2.Text.Trim(); //密码 5 6 if (string.IsNullOrEmpty(strUserName) || string.IsNullOrEmpty(strUserPwd)) 7 { 8 XtraMessageBox.Show("请输入用户名和密码", "Transmate", MessageBoxButtons.RetryCancel); 9 } 10 else 11 { 12 string strPostData = "emailAddress=" + strUserName + "&password=" + strUserPwd+""; 13 14 HttpWebRequest httpWebRequest = WebRequest.Create("http://192.168.1.130:30160/TransmateWebService/login") as HttpWebRequest; 15 16 httpWebRequest.KeepAlive = false; 17 18 byte[] data = System.Text.Encoding.UTF8.GetBytes(strPostData); 19 20 httpWebRequest.Method = "POST"; 21 22 httpWebRequest.ContentLength = data.Length; 23 httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 24 Stream NewStream = httpWebRequest.GetRequestStream(); 25 NewStream.Write(data,0,data.Length); 26 NewStream.Close(); 27 28 HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse; 29 30 Stream ReviceStream = response.GetResponseStream(); 31 StreamReader streamReader = new StreamReader(ReviceStream,Encoding.UTF8); 32 string StrContent = streamReader.ReadToEnd(); 33 34 JObject JsonObject = JObject.Parse(StrContent); 35 string loginCode = JsonObject["errorCode"].ToString(); 36 string TipMessage = JsonObject["message"].ToString(); 37 38 if (loginCode == "200") 39 { 40 XtraMessageBox.Show("登录成功,正在跳转...."); 41 } 42 else 43 { 44 XtraMessageBox.Show("登录失败,请稍候重试"); 45 } 46 }
开始调试了好久,出现下面的错误:
经过不断的查找和调试,主要是少写了一句话:
1 httpWebRequest.ContentType = "application/x-www-form-urlencoded";
希望对大家有帮助,后续会正对HTTP、SOAP、TCP、UDP、Https、等基本协议开一个专题讨论这写问题;
PS :2014、11、17
后来在获取服务器返回的数据时候调试发现,服务器获取的只要是中文的代码,都是乱码;但是Post数据确实是进过UTF-8编码的啊,结果才发现是httpWebRequest.ContentType = "application/x-www-form-urlencoded"; 中并没有添加对内容数据的编码,结果改为:
httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";就正确,一上午就只解决这个问题。希望贴出来,供盆友们不要走弯路