开发者

How to call a web service using HttpWebRequest

开发者 https://www.devze.com 2023-01-02 11:26 出处:网络
I am able to successfully retrieve the wsdl from a server with the code below. How can I now call a method (GetVersion) from this same service?

I am able to successfully retrieve the wsdl from a server with the code below.

How can I now call a method (GetVersion) from this same service?

Trying http://www.servername.com/DataService.asmx/GetVersion returns an error saying the page cannot be found. I have no problem calling the method from a .NET WebService reference, but I'd like to be able to use an HttpWebRequest.

Dim req 开发者_开发问答As HttpWebRequest
Dim resp As HttpWebResponse
Dim sr As IO.StreamReader

req = WebRequest.Create("http://www.servername.com/DataService.asmx?wsdl")
resp = req.GetResponse

sr = New IO.StreamReader(resp.GetResponseStream)
txt.Text = sr.ReadToEnd
sr.Close()


I believe your only problem is the web server's configuration. Each web-service's configuration (web.config file in my case, since i'm using IIS) should allow the management of the protocols allowed to access it: Get, Post, and/or Soap.

I've just tested my own web-service and it replies to GET requests from my browser... It also answers as expected to POST requests ( I adapted some code from https://web.archive.org/web/20210619192654/https://www.4guysfromrolla.com/articles/022410-1.aspx into the following snippet: )

    Dim payload As Byte()
    payload = Text.Encoding.ASCII.GetBytes("paramName=firstValue&p2=secondValue")

    Dim webRequest As System.Net.HttpWebRequest
    webRequest = System.Net.HttpWebRequest.Create("http://www.servername.com/DataService.asmx/GetVersion")
    webRequest.Method = "POST"
    webRequest.KeepAlive = False
    webRequest.ContentType = "application/x-www-form-urlencoded"
    webRequest.ContentLength = payload.Length

    Dim reqStream As System.IO.Stream
    reqStream = webRequest.GetRequestStream()
    reqStream.Write(payload, 0, payload.Length)
    reqStream.Close()

    Dim webResponse As System.Net.HttpWebResponse
    webResponse = webRequest.GetResponse()

    Dim reader As System.IO.StreamReader
    reader = New System.IO.StreamReader(webResponse.GetResponseStream())
    Dim xmlDoc As System.Xml.XmlDocument
    xmlDoc = New System.Xml.XmlDocument()
    xmlDoc.LoadXml(reader.ReadToEnd())

Good luck.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号