Posting data to a web-page with VB.net

I’ve been doing some tryouts on posting data to a xml-rpc.php page – and, I found it quite difficult to find info on the Internet on how to post to a webpage using vb.net. So, I gathered some from around, and made this simple thing:

Public Function PostXML(ByVal url As String, ByVal strXML As String) As String

Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(strXML)

Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)

Dim returnstring As String = Nothing

request.Method = WebRequestMethods.Http.Post

request.ContentLength = bytes.Length

request.ContentType = “text/xml”

Using requeststream As Stream = request.GetRequestStream

requeststream.Write(bytes, 0, bytes.Length)

End Using

Dim response As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)

If Not response.StatusCode = HttpStatusCode.OK Then

Return “Failed connection to xml-rpc.”

Else

Dim receivestream As Stream = response.GetResponseStream

Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding(“utf-8″)

‘ Pipe the stream to a higher level stream reader with the required encoding format.

Dim readStream As New StreamReader(receivestream, encode)

Dim read(256) As [Char]

‘ Read 256 charcters at a time .

Dim count As Integer = readStream.Read(read, 0, 256)

While count > 0

‘ Dump the 256 characters on a string and display the string onto the console.

Dim str As New [String](read, 0, count)

returnstring += str

count = readStream.Read(read, 0, 256)

End While

Return returnstring

‘ Release the resources of stream object.

readStream.Close()

 

End If

response.Close()

request = Nothing

End Function

Leave a Comment