欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【后端C#】后台通过http post 调用 webservice 的方法

程序员文章站 2022-06-13 08:02:36
定义http post 调用webservice的某个方法 调用实例: ......

定义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         }