码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2014-10-31 13:47:47      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:winform   style   blog   http   io   color   os   ar   for   

       本来从来没有仔细研究过Http协议,今天因为公司业务需求,调试了半天,终于现在会Winform用Http协议与服务端通信了,其中常用的有POST和Get方式;

仔细看了人人网和新浪等大部分都是采用GET方式获取数据的,MSN截图如下:

bubuko.com,布布扣

 还是不要脱离本文的主要目的:

  模拟实现登录代码如下:

 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 }

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

bubuko.com,布布扣

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

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

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

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

标签:winform   style   blog   http   io   color   os   ar   for   

原文地址:http://www.cnblogs.com/QQ931697811/p/4064788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!