C#调用WebService的简单方式
2016-05-11 14:31
585 查看
WebServiceCallpublic class WebServiceCall { public void Call() { string url = "http://localhost:1117/WebSite/WebService.asmx"; string data = GetSOAPReuquestBody("100"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "text/xml; charset=utf-8"; req.Method = "POST"; using (Stream reqStream = req.GetRequestStream()) { byte[] reqData = Encoding.UTF8.GetBytes(data); reqStream.Write(reqData, 0, reqData.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Console.WriteLine(resp.StatusCode); foreach (var item in resp.Headers.AllKeys) { Console.WriteLine(item + " : " + resp.Headers[item]); } using (StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { Console.WriteLine(reader.ReadToEnd()); } } public void Call2() { string url = "http://localhost:1117/WebSite/WebService.asmx/GetNumber"; string data = "id=3"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; using (Stream reqStream = req.GetRequestStream()) { byte[] reqData = Encoding.UTF8.GetBytes(data); reqStream.Write(reqData, 0, reqData.Length); } HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Console.WriteLine(resp.StatusCode); foreach (var item in resp.Headers.AllKeys) { Console.WriteLine(item + " : " + resp.Headers[item]); } using (StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.UTF8)) { Console.WriteLine(reader.ReadToEnd()); } } public string GetSOAPReuquestBody(string param) { StringBuilder soap = new StringBuilder(); soap.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); soap.Append("<soap12:Envelope xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); soap.Append("<soap12:Body>"); soap.Append("<GetNumber xmlns=\"http://tempuri.org/\">"); soap.Append("<id>"); soap.Append(param); soap.Append("</id>"); soap.Append("</GetNumber>"); soap.Append("</soap12:Body>"); soap.Append("</soap12:Envelope>"); return soap.ToString(); } }
http://www.cnblogs.com/disappearwind/articles/2633760.html
相关文章推荐
- C# WinForm TreeListView控件用法初步
- SignalR实现web在线即时聊天(C#)
- C#制作、打包、签名、发布Activex全过程【转】
- C# Form内存回收
- 【C#设计模式-责任链模式】
- C# 动态显示曲线
- c#中开发ActiveX的学习笔记【转】
- C#中Monitor和Lock以及区别
- C# winform Listbox添加和删除items
- 分享C#中几个可用的类
- C#程序输出信息到调试窗口的几种方式
- C#中Timer使用及解决重入问题
- C#运算符之与,或,异或及移位运算
- C#面向对象设计的七大原则
- C#开发中怎么提升excel导出速度
- C#实现简单的汽车租赁系统
- C# 委托 delegate
- c#中取整,向上取,向下取
- C# 判断文件夹存在与否并创建文件夹
- C#中的invoke和begininvoke