首页 > 代码库 > winform 客户端 HTTP协议与服务端通信

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 else11 {12 string strPostData = http://www.mamicode.com/"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 =http://www.mamicode.com/ 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 else43 {44 XtraMessageBox.Show("登录失败,请稍候重试");45 }46 }

 开始调试了好久,出现下面的错误:

经过不断的查找和调试,主要是少写了一句话:

1                     httpWebRequest.ContentType = "application/x-www-form-urlencoded";

希望对大家有帮助,后续会正对HTTP、SOAP、TCP、UDP、Https、等基本协议开个专题【敬请期待。。。】

winform 客户端 HTTP协议与服务端通信