Table of Contents

24.2.4.0 Class HTTPClient

This class provides an HTTP client that sends requests to an HTTP server and receives its response.

To create a new HTTP client:

Dim hHTTPClient As HTTPClient
hHTTPClient = New HTTPClient() As "hHTTPClient"  ' → Ereignisname (optional)

24.2.4.0.1 Selected Properties

The HTTPClient class has these properties:

PropertyData typeDescription
AuthIntegerReturns the HTTP authentication mode or the mode set. It can be one of the following constants: Net.AuthNone for no authentication (default), Net.AuthBasic for basic authentication or Net.AuthNTLM for NTLM authentication.
AsyncBooleanReturns or sets whether the FTP/HTTP request is handled asynchronously. Requests are asynchronous by default.
BlockingBooleanReturns or sets whether the stream is blocked. If this property is set, reading from the stream is blocked if there is nothing to read. Writing to the stream is blocked if, for example, the internal system buffer is full.
BufferSizeIntegerReturns or sets the preferred receive buffer size between 0 and 512 KB. If set to zero, the receive buffer size has its default value, which is 16 kB according to the libcurl documentation.
ByteOrderIntegerReturns or sets the byte order used to read or write binary data to the data stream. The property can have the following values: gb.BigEndian or gb.LittleEndian.
CodeIntegerReturns the HTTP status code sent by the server.
CookiesFileStringReturns or sets the file to use for reading and saving cookies. If no file is set, cookies are not persistent. Cookies are only saved if the property 'UpdateCookies' is also set.
DebugBooleanReturns the value or sets the debugging mode. For example, if this property is set, a client object prints all commands sent to the server to the console of the IDE.
EncodingStringReturns or sets the HTTP header “Accept-Encoding”.
HeadersString[ ]Returns the HTTP headers in a string array.
ReasonStringReturns the HTTP reason string. This is the string that follows the error code in an HTTP response.
RedirectBooleanReturns or sets the value of whether the HTTPClient must follow HTTP redirects. By default, redirects are not followed.
UpdateCookiesBooleanReturns the value or sets whether cookies need to be updated. The default value is False. The CookiesFile property must be set (before), otherwise cookies will not be saved.
UserAgentStringReturns or sets the UserAgent used for the request. The currently used UserAgent is 'Gambas/3.17 (gb.net.curl; Linux)'.
DownloadedLongReturns the number of bytes already downloaded from the server.
TotalDownloadedLongReturns the total number of bytes expected to be downloaded.
UploadedLongReturns the number of bytes that have already been uploaded.
TotalUploadedLongReturns the total number of bytes expected to be uploaded.
ErrorTextStringReturns the error string associated with the error code returned by the curl library.
UserStringReturns or sets the user used for authorisation.
PasswordStringReturns or sets the password used for authorisation.
TargetFileStringReturns or sets the target file used for download operations. This is an equivalent of the optional TargetFile argument of the download method of the HTTPClient class.
TimeoutIntegerReturns or sets the client timeout in seconds. The request is aborted if it takes more than the specified number of seconds. If the value is zero, no timeout is defined. Don't forget to set this property if it is a *synchronous* request, otherwise the client may wait forever for the server.
StatusIntegerReturns the status of the client. It can be one of the following values: Net.Inactive: The client is inactive. Net.ReceivingData: The client is receiving data from the network. Net.Connecting: The client is connecting to the server. The status has a negative value if an error has occurred. The value of the status is actually -1000 minus the libcurl error code. Most of these error codes have a corresponding constant in the Net class. To know exactly what an error code means, you need to look at the libcurl error code list.

Table 24.2.4.0.1 : Properties of the HTTPClient class

24.2.4.0.2 Methods

The HTTPClient class has the static method DownLoad(…):

Static Function Download ( URL As String [ , Headers As String[] ] ) As String

- URL ist die Adresse
- Headers ist ein optionales String-Array der verwendeten Header

The HTTPClient class has these selected methods:

MethodDescription
Head ( [ Headers As String[]] )This method makes a call to the HTTP server using the default method 'HEAD'. Before using this method, you must fill the URL property with the desired host name and the document to be retrieved. 'Headers' is an optional string array of HTTP headers that are sent to the server with the request.
Post ( ContentType As String, Data As String [ , Headers As String[], TargetFile As String ] )This method makes a call to the http server with the default method 'POST'. Before you can use it, you must fill the URL property with the desired hostname and the document to retrieve.
Get ( [ Headers As String[], TargetFile As String ] )This method performs a request to the HTTP server with the default method 'GET'. Before using this method, you must fill the URL property with the desired host name and the document to be retrieved.
CopyFrom ( HttpClient As Source )Fills the HttpClient object with the properties of another HttpClient object. The parameter 'HttpClient' returns the source HttpClient object.
Put ( ContentType As String, Data As String [ , Headers As String[], TargetFile As String ] )Sends data with the “PUT” method to a specified URL.
PostFile ( ContentType As String, Path As String [ , Headers As String[], TargetFile As String ] )You can send a file via a POST request.

Table 24.2.4.0.2 : Methods of the HTTPClient class

Notes * * Post ( ContentType As String, Data As String [ , Headers As String[], TargetFile As String ] ):

24.2.4.0.3 Events

The HTTPClient class has these events:

EventDescription
Cancel ( )This event is triggered when a request is cancelled.
Connect ( )This event is triggered when the connection is established.
Error ( )This event is triggered when an error (from the CURL library) is returned.
Finished ( )The event is triggered when a command has finished correctly.
Progress ( )This event is triggered periodically when something is downloaded or uploaded.
Read()This event is triggered when data has been received.

Table 24.2.4.0.3 : Events of the HTTPClient class

24.2.4.0.4 Example - HTTP Client

In the example, the Get() method is used without parameters. Therefore, the data received from the HTTP server is stored in memory. This data is accessed with standard stream methods. The website data is manageably small and is displayed in a text box:

BILD
Figure 24.2.4.0.1: Output of the external IP address.

This is the complete source code:

[1] ' Gambas class file
[2]
[3] Public Sub Form_Open()
[4]
[5]     MAdditional.CheckNetwork()
[6]     FMain.Caption = ("Current external IP address")
[7]
[8] '-- Note the text on this web page: https://ipecho.net/developers.html
[9]     lblIPAdress.Text = HTTPGetIP("https://ipecho.net/plain")
[10]
[11] End
[12]
[13] Public Function HTTPGetIP(argURL As String) As String
[14]
[15]     Dim hHTTPClient As HttpClient
[16]     Dim sResult As String
[17]
[18]     hHTTPClient = New HttpClient
[19]     hHTTPClient.URL = argURL
[20]     hHTTPClient.Async = False
[21]     hHTTPClient.TimeOut = 10
[22]
[23]     hHTTPClient.Get()
[24]
[25]     If Lof(hHTTPClient) Then sResult = Read #hHTTPClient, Lof(hHTTPClient)
[26]
[27]     Return sResult
[28]
[29] End

Comment:

The project uses the module MAdditional, which contains this procedure, among others:

Public Sub CheckNetwork()
 
    Dim sResponse, sCommand As String
    Dim sIPAddress As String
 
'-- With Desktop.NetworkAvailable (gb.desktop) you can determine whether a network connection exists.
    If Not Desktop.NetworkAvailable Then
       Message.Error(("No network available!<hr>The application will be terminated."))
       Quit
    Endif
 
'-- Check connection to local router by trying to obtain the IP address of the gateway
    sCommand = "route -n | grep ^0.0.0.0 | awk '{print $2}'"
    Shell sCommand To sIPAddress
    If Not sIPAddress Then
       Message.Error(("No connection to lokal router!<hr>The application will be terminated."))
       Quit
    Endif
 
    sCommand = "ping -c 1 8.8.8.8"
    Shell sCommand To sResponse
    If Not InStr(sResponse, "8.8.8.8 ping") Then
       Message.Error(("No connection to the Internet!<hr>The application will be terminated."))
       Quit
    Endif
 
End

Download

Projects

Download