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

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

仔细看了人人网和新浪等大部分都是采用GET方式获取数据的;

 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 }

 

posted on 2015-03-26 18:35  夜雨梧桐  阅读(1711)  评论(0编辑  收藏  举报

导航