博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

定义http post 调用webservice的某个方法

 1 /// <summary>    
 2     /// http Post调用  WebService  
 3     /// </summary>    
 4     public static XmlDocument Test1_QueryPostWebService(String URL,
 5         String MethodName, Hashtable Pars)
 6     {
 7         
 8  
 9  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
10         request.Method = "POST";
11         request.ContentType = "application/x-www-form-urlencoded";
12         request.Credentials = CredentialCache.DefaultCredentials;
13         request.Timeout = 10000;
14  
15         #region 参数拼接成字符串,最后编码
16         StringBuilder sb = new StringBuilder();
17         foreach (string k in Pars.Keys)
18         {
19             if (sb.Length > 0)
20             {
21                 sb.Append("&");
22             }
23             sb.Append(
24                 HttpUtility.UrlEncode(k) + "="
25                 + HttpUtility.UrlEncode(Pars[k].ToString())
26                 );
27  
28         }
29         byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
30         #endregion
31  
32         #region  把编码后的参数写入请求流中
33         request.ContentLength = data.Length;
34         Stream writer = request.GetRequestStream();
35         writer.Write(data, 0, data.Length);
36         writer.Close();
37         #endregion
38  
39         #region 读取结果,创建XmlDocument对象,对象加载结果
40         var response = request.GetResponse();
41         StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
42         String retXml = sr.ReadToEnd();
43         sr.Close();
44         XmlDocument doc = new XmlDocument();
45         doc.LoadXml(retXml);
46         #endregion 
47  
48   return doc;
49  
50  
51  
52     }
53  

调用实例:

 1 protected void Page_Load(object sender, EventArgs e)
 2         {
 3             Hashtable pars = new Hashtable();
 4             String Url = "http://localhost:63596/WebService1.asmx";
 5             pars["aa"] = "HelenZhou";
 6             XmlDocument doc = WebSvcCaller.
 7                 Test1_QueryPostWebService(Url,
 8                 "MyHelloWorld",
 9                 pars);
10             Response.Write(doc.OuterXml); 
11         }