在一般的系统中,用户登录大部分都是简单的获取用户名和密码,然后到数据库查询。但是一两个系统的话,可以去访问数据库,然后来获取测试结果。如果是五个,六个系统,甚至更多的系统,都需要建立自己的用户表,而用户可能是一样的。这样的情况下,可能造成一部分的设计麻烦或者代码冗余。但是如果换种方式,有一个标准的数据库,它里面的用户是最最标准的,这个数据库提供给其它系统一个webService,当其它用户登录的时候,系统只需要去访问一个地址,然后传入用户名和密码,静等返回结果。这样的处理,是不是大大的提高了访问效率,也分了层,提高了代码的可维护性。

   你可以把你的代码考虑为一个简单的浏览器,然后通过浏览器去登录系统,具体登录成功还是失败,就看系统的返回结果了。具体怎么实现呢?看下面的这个方法

View Code
 1  /// <summary>
 2         /// HTTP Request登录请求
 3         /// </summary>
 4         /// <param name="param">可以为空</param>
 5         /// <param name="username">用户名(社员号)</param>
 6         /// <param name="password">密码</param>
 7         /// <returns></returns>
 8         public string SendRequest(string param, string username, string password)
 9         {
10             try
11             {
12                 string url = "http://192.168.1.221/LoginValidateSystem/LoginIndex.aspx?EmployeeCD1="
13                                 + "" + username + "&EmployeePassword1=" + password + "";//请求的链接地址
14                 ASCIIEncoding encoding = new ASCIIEncoding(); 
15                 byte[] data = encoding.GetBytes(param); //将参数转换为字节数组
16                 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
17                 request.Method = "POST";//请求方式
18                 request.ContentType = "application/x-www-form-urlencoded";//请求连接的类型
19                 request.ContentLength = data.Length; //请求参数的长度
20                 Stream sm = request.GetRequestStream(); //以数据流的形式传递参数
21                 sm.Write(data, 0, data.Length);
22                 sm.Close();
23                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
24                 if (response.StatusCode.ToString() != "OK")
25                 {
26                     return "";
27                 }
28                 StreamReader myreader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //以数据流的形式获取response响应的数据
29                 string responseText = myreader.ReadToEnd();
30                 return responseText;
31             }
32             catch (Exception)
33             {
34                 
35                 throw;
36             }
37         }  

 具体应用中,用到了一些HTTP的知识。真正用起来后会感觉真的方便很多。

posted on 2012-12-14 15:53  kevenYuan  阅读(529)  评论(0编辑  收藏  举报