工作中点滴记录

永远保持学徒心态

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

如果调用WebService的不是在.NET中,无法直接添加web引用,那怎么调用webservice。

有两种方式

第一种方式:GET方式

GET方式
 1   string strUrl = "http://127.0.0.1/rss/webservice.asmx/GetNews?topNum=2";
 2         HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create(strUrl);
 3         hwrq.Method = "GET";
 4         HttpWebResponse hwrp = (HttpWebResponse)hwrq.GetResponse();
 5         Stream stream = hwrp.GetResponseStream();
 6         XmlDocument doc = new XmlDocument();
 7         doc.Load(stream);
 8         string strLine = "";
 9         XmlNodeList list = doc.GetElementsByTagName("Table");
10         for (int i = 0; i < list.Count; i++)
11         {
12             XmlNodeList chlist = list[i].ChildNodes;
13             for (int j = 0; j < chlist.Count; j++)
14             {
15                 strLine = strLine + chlist[j].Name + "\t" + chlist[j].InnerText + "\n";
16             }
17             strLine = strLine + "\n";
18         }
19         StreamWriter sw = new StreamWriter(@"c:/c.txt");
20         sw.WriteLine(strLine);
21         sw.Flush();
22         sw.Close();

第二种方式:POST方式

POST方式
 1 string strUrl = "http://127.0.0.1/rss/webservice.asmx/GetNews";
 2         HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create(strUrl);
 3         hwrq.Method = "POST";
 4         hwrq.ContentType = "application/x-www-form-urlencoded";
 5         String param1 = HttpUtility.UrlEncode("topNum");
 6         param1 += "=" + HttpUtility.UrlEncode("5");
 7         byte[] bt = Encoding.UTF8.GetBytes(param1);
 8         hwrq.ContentLength = bt.Length;
 9         Stream sw = hwrq.GetRequestStream();
10         sw.Write(bt, 0, bt.Length);
11         sw.Close();
12         HttpWebResponse hwrp = (HttpWebResponse)hwrq.GetResponse();
13         Stream stream = hwrp.GetResponseStream();
14         XmlDocument xmldoc = new XmlDocument();
15         xmldoc.Load(stream);
16         XmlNodeList list = xmldoc.GetElementsByTagName("Table");
17         string strLine = "";
18         for (int i = 0; i < list.Count; i++)
19         {
20             XmlNodeList chlist = list[i].ChildNodes;
21             for (int j = 0; j < chlist.Count; j++)
22             {
23                 strLine = strLine + chlist[j].Name + "\t" + chlist[j].InnerText + "\n";
24             }
25             strLine = strLine + "\n";
26         }
27         StreamWriter writer = new StreamWriter(@"c:\c.txt");
28         writer.WriteLine(strLine);
29         writer.Flush();
30         sw.Close();

get方式与post方式的主要区别在于post方式的参数要经过url编码,并在获得请求之前传送。

post的方式的参数一定要以实例中方式来写,否则会出现HTTP请求500错误。

string param1 = HttpUtility.UrlEncode("topNum");

param1+="="+HttpUtility.UrlEncode("5");

posted on 2012-09-16 21:00  梦里故乡  阅读(20594)  评论(3编辑  收藏  举报