码迷,mamicode.com
首页 > Web开发 > 详细

发送Http请求调用webService

时间:2019-11-23 13:01:13      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:lin   child   response   enc   ebs   ldo   www   news   rss   

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

有两种方式

第一种方式:GET方式

  string strUrl = "http://127.0.0.1/rss/webservice.asmx/GetNews?topNum=2";
        HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create(strUrl);
        hwrq.Method = "GET";
        HttpWebResponse hwrp = (HttpWebResponse)hwrq.GetResponse();
        Stream stream = hwrp.GetResponseStream();
        XmlDocument doc = new XmlDocument();
        doc.Load(stream);
        string strLine = "";
        XmlNodeList list = doc.GetElementsByTagName("Table");
        for (int i = 0; i < list.Count; i++)
        {
            XmlNodeList chlist = list[i].ChildNodes;
            for (int j = 0; j < chlist.Count; j++)
            {
                strLine = strLine + chlist[j].Name + "\t" + chlist[j].InnerText + "\n";
            }
            strLine = strLine + "\n";
        }
        StreamWriter sw = new StreamWriter(@"c:/c.txt");
        sw.WriteLine(strLine);
        sw.Flush();
        sw.Close();

 

第二种方式:POST方式

string strUrl = "http://127.0.0.1/rss/webservice.asmx/GetNews";
        HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create(strUrl);
        hwrq.Method = "POST";
        hwrq.ContentType = "application/x-www-form-urlencoded";
        String param1 = HttpUtility.UrlEncode("topNum");
        param1 += "=" + HttpUtility.UrlEncode("5");
        byte[] bt = Encoding.UTF8.GetBytes(param1);
        hwrq.ContentLength = bt.Length;
        Stream sw = hwrq.GetRequestStream();
        sw.Write(bt, 0, bt.Length);
        sw.Close();
        HttpWebResponse hwrp = (HttpWebResponse)hwrq.GetResponse();
        Stream stream = hwrp.GetResponseStream();
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(stream);
        XmlNodeList list = xmldoc.GetElementsByTagName("Table");
        string strLine = "";
        for (int i = 0; i < list.Count; i++)
        {
            XmlNodeList chlist = list[i].ChildNodes;
            for (int j = 0; j < chlist.Count; j++)
            {
                strLine = strLine + chlist[j].Name + "\t" + chlist[j].InnerText + "\n";
            }
            strLine = strLine + "\n";
        }
        StreamWriter writer = new StreamWriter(@"c:\c.txt");
        writer.WriteLine(strLine);
        writer.Flush();
        sw.Close();

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

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

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

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

 

发送Http请求调用webService

标签:lin   child   response   enc   ebs   ldo   www   news   rss   

原文地址:https://www.cnblogs.com/Violety/p/11917296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!