< C# Http Post Request Program Example | Main | Asynchronous HTTP & Misc. >


 

Chapter 10 Part 7:

HTTP with .NET

 

 

What do we have in this chapter 10 Part 7?

  1. VB .NET Http Post Request Program Example

 

VB .NET Http Post Request Program Example

 

Create a new class library project and you might want to use HttpPostRequestVB as the project and solution names.

 

VB .NET Http Post Request Program Example - a new class library project creation in Visual Studio IDE

 

 

Rename the source file to HttpPostRequest to reflect the application that we want to develop.

 

VB .NET Http Post Request Program Example - renaming the source file

 

Add the following Imports directives.

 

Imports System

Imports System.Net

Imports System.IO

Imports System.Text

Imports System.Web

 

Add the HttpPostRequest class code that include the Main() subroutine.

 

' Simple class that encapsulates the HTTP post sample.

Public Class HttpPostRequest

    ' Displays simple usage information.       

    Shared Sub usage()

        Console.WriteLine("Executable_file_name [-u URL] [-d data] [-s file] [-p proxy]")

        Console.WriteLine("Available options:")

        Console.WriteLine("     -u URL          URL to post data to")

        Console.WriteLine("     -d data         Data to post")

        Console.WriteLine("     -s file         File name to save response to")

        Console.WriteLine("     -p HTTP URL     Proxy to use for post operation")

        Console.WriteLine()

    End Sub

 

    ' This routine validates the data being posted to the web page. It parses

    ' the string for reserved characters '?', '=', and '&'. The individual

    ' validated parts are returned via a StringBuilder object.       

    ' <param name="postData">Data to validate</param>

    ' <returns>StringBuilder object representing the parsed elements</returns>

    Public Function ValidatePostData(ByVal postData As String) As StringBuilder

        Dim encodedPostData As StringBuilder = New StringBuilder()

        ' These characters should be more out there...

        Dim reservedChars() As Char = {"?", "=", "&", "+"}

        Dim pos As Integer

        Dim offset As Integer

 

        ' Validate the data to be posted

        Console.WriteLine("Validating the data to be posted...")

        offset = 0

        While (offset < postData.Length)

            pos = postData.IndexOfAny(reservedChars, offset)

            If (pos = -1) Then

                ' Append the remaining part of the string

                Console.WriteLine("Appending the remaining part of the string...")

                encodedPostData.Append(HttpUtility.UrlEncode( _

                    postData.Substring(offset, postData.Length - offset)))

                Exit While

            End If

            ' Found a special character so append up to the special character

            Console.WriteLine("Found a special character so append up to the special character...")

            encodedPostData.Append(HttpUtility.UrlEncode( _

                postData.Substring(offset, pos - offset)))

            encodedPostData.Append(postData.Substring(pos, 1))

            offset = pos + 1

        End While

        ValidatePostData = encodedPostData

    End Function

 

    ' This method creates an HttpWebRequest object, sets the method to "POST",

    ' and builds the data to post. Once the HttpWebRequest object is created,

    ' the request stream is obtained and the post data is sent and the

    ' request stream closed. The response is then retrieved.       

    ' <param name="postUrl">URL to post data to</param>

    ' <param name="postData">Data to post</param>

    ' <param name="proxyServer">Proxy server to use</param>

    ' <param name="saveFile">Filename to save response to</param>

    Public Sub HttpMethodPost( _

        ByVal postUrl As String, _

        ByVal postData As String, _

        ByVal proxyServer As IWebProxy, _

        ByVal saveFile As String)

 

        Dim httpRequest As HttpWebRequest = Nothing

        Dim httpResponse As HttpWebResponse = Nothing

        Dim httpPostStream As Stream = Nothing

        Dim httpResponseStream As BinaryReader = Nothing

        Dim localFile As FileStream = Nothing

 

        Try

            Dim encodedPostData As StringBuilder

            Dim postBytes() As Byte = Nothing

 

            ' Create HTTP web request

            Console.WriteLine("Creating HTTP web request...")

            httpRequest = CType(WebRequest.Create(postUrl), HttpWebRequest)

            ' Change method from the default "GET" to "POST"

            Console.WriteLine("Changing method from the default GET to POST...")

            httpRequest.Method = "POST"

            ' Posted forms need to be encoded so change the content type  

            Console.WriteLine("Changing the content type (encoding)...")

            httpRequest.ContentType = "application/x-www-form-urlencoded"

            ' Set the proxy

            Console.WriteLine("Setting the proxy...")

            httpRequest.Proxy = proxyServer

            ' Validate and encode the data to POST

            Console.WriteLine("Validating and encode the data to POST...")

            encodedPostData = ValidatePostData(postData)

 

            Console.WriteLine("Encoded POST string: '{0}'", encodedPostData.ToString())

 

            ' Retrieve a byte array representation of the data

            Console.WriteLine("Retrieving a byte array representation of the data...")

            postBytes = Encoding.UTF8.GetBytes(encodedPostData.ToString())

            ' Set the content length (the number of bytes in the POST request)

            Console.WriteLine("Setting the content length - the number of bytes in the POST request...")

            httpRequest.ContentLength = postBytes.Length

            ' Retrieve the request stream so we can write the POST data

            Console.WriteLine("Retrieving the request stream so we can write the POST data...")

            httpPostStream = httpRequest.GetRequestStream()

            ' Write the POST request

            Console.WriteLine("Writing the POST request...")

            httpPostStream.Write(postBytes, 0, postBytes.Length)

 

            httpPostStream.Close()

            httpPostStream = Nothing

 

            ' Retrieve the response

            Console.WriteLine("Retrieving the response...")

            httpResponse = CType(httpRequest.GetResponse(), HttpWebResponse)

            ' Retrieve the response stream

            Console.WriteLine("Retrieving the response stream...")

            httpResponseStream = New BinaryReader( _

                httpResponse.GetResponseStream(), _

                Encoding.UTF8 _

                )

 

            Dim readData() As Byte

 

            ' Open the file to save the response to

            Console.WriteLine("Opening the file to save the response to...")

            localFile = File.Open( _

                saveFile, _

                System.IO.FileMode.Create, _

                System.IO.FileAccess.Write, _

                System.IO.FileShare.None _

                )

            Console.WriteLine("Saving response to: {0}", localFile.Name)

            Console.WriteLine("Receiving response...")

 

            ' Receive the response stream until the end

            Console.WriteLine("Receiving the response stream until the end...")

            Dim count As Integer = 0

            Dim percent As Long

 

            While (True)

                readData = httpResponseStream.ReadBytes(4096)

                If (readData.Length = 0) Then

                    Exit While

                End If

 

                localFile.Write(readData, 0, readData.Length)

 

                ' Calculate the progress and display to the console

                count += readData.Length

                percent = (count * 100) / httpResponse.ContentLength

 

                ' Console.WriteLine(" ")

                Console.WriteLine("{0}% progress...", percent.ToString().PadLeft(2))

            End While

            Console.WriteLine()

        Catch wex As WebException

            Console.WriteLine("Exception occurred: {0}", wex.ToString())

            httpResponse = CType(wex.Response, HttpWebResponse)

        Finally

            ' Close any remaining resources

            Console.WriteLine("Closing any remaining resources...")

            If (Not IsNothing(httpResponse)) Then

                httpResponse.Close()

            End If

            If (Not IsNothing(localFile)) Then

                localFile.Close()

            End If

        End Try

    End Sub

 

    ' This is the main routine that parses the command line and calls routines to

    ' issue the POST request and receive the response.

    ' <param name="args">Command line arguments</param>

    Shared Sub Main()

        Dim proxyServer As IWebProxy

        Dim uriToPost As String = "http://search.msdn.microsoft.com/"

        Dim proxyName As String = Nothing

        Dim postData As String = "Default.aspx?Query=web.dll"

        Dim fileName As String = Nothing

        ' Parse the command line

        Dim args As String() = Environment.GetCommandLineArgs()

        Dim i As Integer

 

        usage()

 

        For i = 1 To args.GetUpperBound(0)

            Try

                Dim CurArg() As Char = args(i).ToCharArray(0, args(i).Length)

                If (CurArg(0) = "-") Or (CurArg(0) = "/") Then

                    Select Case Char.ToLower(CurArg(1), System.Globalization.CultureInfo.CurrentCulture)

                        Case "u"

                            ' URI to post to

                            i = i + 1

                            uriToPost = args(i)

                        Case "p"

                            ' Name of proxy server to use

                            i = i + 1

                            proxyName = args(i)

                        Case "d"

                            ' Retrieve all referenced images and text on the same host

                            i = i + 1

                            postData = args(i)

                        Case "s"

                            ' Local save path to append to retrieved resources

                            i = i + 1

                            fileName = args(i)

                        Case Else

                            usage()

                            Exit Sub

                    End Select

                End If

            Catch e As Exception

                usage()

                Exit Sub

            End Try

        Next

        Try

            Dim httpPost As HttpPostRequest = New HttpPostRequest()

 

            ' Set the proxy if supplied or use the default IE static proxy

            Console.WriteLine("Setting the proxy if supplied or use the default IE static proxy...")

            If (IsNothing(proxyName)) Then

                proxyServer = WebRequest.DefaultWebProxy

            Else

                ' Must cast it to IWebProxy if needed, not done here

                proxyServer = New WebProxy(proxyName)

            End If

            ' Post the request and write the response to the file

            Console.WriteLine("Posting the request and write the response to the file...")

            httpPost.HttpMethodPost(uriToPost, postData, proxyServer, fileName)

        Catch ex As Exception

            Console.WriteLine("Exception occurred: {0}", ex.Message)

        End Try

    End Sub

End Class

 

 

 

 

Build the project. Well, in this case the following error displayed. The System.Web in the Imports directive seems not working.

 

error BC30451: Name 'HttpUtility' is not declared.

 

Let try adding the System.Web manually. Select the project folder > Right click mouse > Select Add Reference context menu.

 

VB .NET Http Post Request Program Example - invoking the Add Reference page

 

In the .NET tab, select the System.Web and click the OK button.

 

VB .NET Http Post Request Program Example - selecting the System.Web (Web.dll) component

 

To test this program we need to change the DLL to the application (EXE) type program so that we can run it from the command prompt. Select the project folder > Right click mouse > Select Properties context menu.

 

VB .NET Http Post Request Program Example - invoking the project's property page

 

Change the Application type: to Console Application and the Startup object: to Sub Main.

 

VB .NET Http Post Request Program Example - changing the Application type: to Console Application and the Startup object: to Main() subroutine

 

Build and run the project.

 

VB .NET Http Post Request Program Example - bilding the project  

 

The following is the output sample using the default argument values.

 

VB .NET Http Post Request Program Example - a sample output using default argument values

 

The following output sample is based on the following arguments:

 

httppostrequestvb -u http://search.msdn.microsoft.com/ -d Default.aspx?Query=web.dll -s testvb.htm

 

VB .NET Http Post Request Program Example - a sample output with supplied argument values

 

The following snapshot is an output sample based on the following arguments:

 

httppostrequestvb -u http://www.google.com/ -d search?as_q=tenouk -s testvb1.htm

 

VB .NET Http Post Request Program Example - another sample output with supplied arguments

 

 

 


 

< C# Http Post Request Program Example | Main | Asynchronous HTTP & Misc. >