WebRequest & WebResponse

WebRequest & WebResponse

There are two methods to send info and get a response via HTTP. The second (alternate) method works for both .NET and VB6, but it requires DLL reference (take your pick between these methods&#151which one is better really just depends on your priorities).

Method 1:

Dim strXml As StringstrXml = "XML= Sample Info To Send" '"XML =" is the field name in thiscase (check documentation of web service)Dim sURL As String = "" 'address of webserviceDim req As HttpWebRequest = HttpWebRequest.Create(sURL) 'you must use theCREATE (NOT New)'Alternate (from MSDN - I didn't test this) ->' Dim req As HttpWebRequest = CType(WebRequest.Create(sURL),HttpWebRequest)req.ContentType = "application/x-www-form-urlencoded" 'header info (again,check documentation of web service)'you must set the ContentLength to send anythingreq.ContentLength = CLng(strXml.Length) 'this defaults to -1 (assumesyou're going to do a GET)'Method property can be set to any of the HTTP 1.1 protocol verbs: GET,HEAD, POST, PUT, DELETE, TRACE, or OPTIONS'Do NOT change the Method property AFTER you've started the request(req.Get...) - will throw error (Invalid Operation Exception)req.Method = "POST"'HttpWebRequest.GetRequestStream is how you "send" stuff -'it gives you a stream you can write to (in this case, easier to use aStreamWriter,'so I create one from the stream)Dim s As Streams = req.GetRequestStream 'gives you a streamDim sw As StreamWriter = New StreamWriter(s)sw.Write(strXml)'you MUST close these NOW, or you can blow up the connection to the webservicesw.Close()s.Close()'Get the responseDim resp As WebResponse = req.GetResponse() 'I could also use aHttpWebResponse here (use CType) - IN THEORY (didn't test)Dim sResp As StreamReader = New StreamReader(resp.GetResponseStream)TextBox1.Text = sResp.ReadToEnd 'display response in textbox'clean upsResp.Close()resp.Close()req = Nothing

The next method is the VB6 equivalent done .NET-style. This method does work, but you need to remember to add a reference to the MSXML DLL (usually in system32 folder?use version 3 at least).

Method 2:

Dim sURL As String = "" 'bogus web serviceaddress - replace with real oneDim strXML As String = "Sample" 'will be XML string to sendDim xmlhttp As New MSXML2.XMLHTTP() 'Start of code to use HTTP"POST", sURL, False) 'POST is the method, sURL is the webservice, False = NOT asyncxmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded") 'headers (and their values) vary byweb service - this is just an examplexmlhttp.send("XML=" & strXML) ' "XML = " is the "field" name in thiscase - varies by web service - again, this is just an example of somethingto sendTextBox1.Text = xmlhttp.responseXML.xml 'puts any response string into atextbox for display


Share the Post: