HttpWebRequest 调用 WebService 返回 xml
WebService:
View Code
1 [WebService(Namespace = "http://tempuri.org/")]
2 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
3 public class WebService : System.Web.Services.WebService {
4
5 public WebService () { }
6
7 [WebMethod]
8 public string getConnectionString()
9 {
10 return "结果信息";
11 }
12 }
后台代码直接调用:
View Code
1 string url = "http://192.168.0.156:10001/WebService.asmx/getConnectionString";
2 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
3 System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
4 String xml=new StreamReader(response.GetResponseStream(),Encoding.UTF8).ReadToEnd();
5 XmlDocument docXml = new XmlDocument();
6 docXml.LoadXml(xml);
7 string str= docXml.ChildNodes[1].InnerText;
结果s:
View Code
1 <?xml version="1.0" encoding="utf-8"?>
2 <string xmlns="http://tempuri.org/">结果信息</string>
注意:
如果IE访问http://192.168.0.156:10001/WebService.asmx/getConnectionString出现如下问题:
“/”应用程序中的服务器错误。 因 URL 意外地以“/getConnectionString”结束,请求格式无法识别。
解决方法是:在网站的web.config下添加如下节点
View Code
1 <webServices>
2 <protocols>
3 <add name="HttpPost"/>
4 <add name="HttpGet"/>
5 </protocols>
6 </webServices>