Posting data from a web service to a web page

Writing and consuming web services is one of the important things we do at work. Systems running a variety of operating systems and with a completely different set of configurations make it difficult to exchange data easily. Things get even worse when there is a difference in time zones. We really didn’t want to wait for our integration partner to come back to us with a feedback whether they received the data or not. We rather decided to take ‘just-try-it” approach to post (HTTP-POST) web service data to a web page on localhost and it worked. I know it is not a rocket science, but it saved me time and effort, so I thought of sharing it.

So, this is what we do to send data to a web service:



Try

stream = File.OpenText( "C:\ServiceData.xml" )
strXML = stream.ReadToEnd()
stream.Close()

webreq = HttpWebRequest.Create("{Web-Service-Uri}")
webreq.Method = "POST"
webreq.ContentType = "application/x-www-form-urlencoded"

strXML = "data=" & HttpUtility.UrlEncode(strXML)
bytes = System.Text.Encoding.UTF8.GetBytes(strXML)
webreq.ContentLength = bytes.Length

requestStream = webreq.GetRequestStream()
requestStream.Write(bytes, 0, bytes.Length)
requestStream.Close()

webResponse = webreq.GetResponse()
responseStream = New IO.StreamReader(webResponse.GetResponseStream())
responseStream.Close()
webResponse.Close()
webreq = Nothing

Catch ex As System.Net.WebException

Dim responseFromServer As [String] = ex.Message.ToString() & " "
If ex.Response IsNot Nothing Then
Using response As Net.WebResponse = ex.Response
Dim data As Stream = response.GetResponseStream()
Using reader As New StreamReader(data)
responseFromServer += reader.ReadToEnd()
End Using
End Udsing
End If
End Try

The above code works fine if you want to send data to a web service. However, to send to a webpage all we have to do is replace the service uri {Web-Service-Uri} on line 07 with web page address, something like this:


webreq = HttpWebRequest.Create("{Web-Service-Uri}") –> Posting to a web service


webreq = HttpWebRequest.Create("http://localhost:1886/service-data-receiver.aspx" ) –> Posting to a web page

The part which I had to figure out was how to access the data sent from a web service to my page. Since the request was not originated by a page-based model, I couldn't use Request.Forms or Request.QueryString. After some research I found that it is just Request object that can be used to access data. Yes, that is it.



Protected Sub Page_Load(ByVal sender As Object , ByVal e As System.EventArgs) Handles Me.Load

Dim response1 As String = HttpUtility.UrlDecode(Request( "data"))Dim doc As XDocument = XDocument.Parse(response1)
doc.Save( "C:\inetpub\wwwroot\service-data-received.xml" )
Response.Write(response1)

End Sub

HTH,

0 comments:

Post a Comment