发送Http请求调用webService

Posted 花落翩翩 岁月荏苒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了发送Http请求调用webService相关的知识,希望对你有一定的参考价值。

如果调用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 + "	" + chlist[j].InnerText + "
";
            }
            strLine = strLine + "
";
        }
        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 + "	" + chlist[j].InnerText + "
";
            }
            strLine = strLine + "
";
        }
        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的主要内容,如果未能解决你的问题,请参考以下文章

如何使用soapUI模拟webservice客户端发送请求

WebService

在c#中,用soap调用webservice,发送消息并取得webservice方法里返回的内容,用http 的方法

js调用webservice接口

C# 通过模拟http请求来调用soapwsdl

客户端怎么测试webservice接口,怎么算测试成功