Hypertext Transfer Protocol Connections  
 

To establish a connection using the HTTP control, you should call the Connect method and check the return value to ensure that the connection was successful. This can be done one of several ways, and which approach you use largely depends on personal preference and the structure of your program.

Method Arguments

You can call the Connect method with a number of different arguments, all of which are optional. The most common use would look like this:

Dim nError As Long

nError = HttpClient1.Connect(strHostName)
If nError > 0 Then
    MsgBox HttpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

In this example, the strHostName string variable contains the name of the server to connect to. If the method returns a value other than zero, this indicates an error and a message box is used to display the error to the user. Note that if the resource requires authentication, then a username and password can also be passed to the method.

Property Values

Another method is to set the host name using the control's HostName property and then calling the Connect method without any arguments. Here is an example of how that could be done:

Dim nError As Long

HttpClient1.HostName = "www.microsoft.com"

nError = HttpClient1.Connect()
If nError > 0 Then
    MsgBox HttpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

Note that the RemotePort property is not specified, which means that the default port number should be used. If authentication was required, the UserName and Password properties could be set as well. As with the previous example, if the connection fails then the method will return an error code and a message box is displayed to the user.

Uniform Resource Locators

A third approach is to specify a URL by setting the URL property and then calling the Connect method without any arguments. By setting the URL property, the control will automatically update the various related properties such as HostName and RemotePort. Here is an example of how this could be done:

Dim nError As Long

HttpClient1.URL = "http://www.microsoft.com/"

nError = HttpClient1.Connect()
If nError > 0 Then
    MsgBox HttpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

If you prefer to use URLs, this approach provides the simplest means of establishing the connection. It should be noted that if the URL property is assigned an invalid value, then the control will throw an exception. If you are using URLs provided by a user, it is strongly recommended that you implement an error handler, otherwise your program may terminate if the user specifies an incorrect or incomplete URL.