User Tools

Site Tools


Sidebar

Network and communication

k24:k24.2:k24.2.4:start

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 ] ):

  • ContentType is the MIME type of the data. Data is the data to be set. Headers is an optional string array of HTTP headers. TargetFile is an optional file to which the response will be written. If TargetFile is not specified, the data received from the server is stored in memory. You can access the data using the standard stream methods or the peek method on the document. If TargetFile is specified, the data received from the server is stored in the specified file and is not available in the internal memory buffer. If you want to transmit form data, use 'application/x-www-form-urlencoded' as the ContentType header of the request. Then format the 'Data' parameter with a string using the following syntax: Key1=Value1&Key2=Value2&… .
  • Get ( [ Headers As String[], TargetFile As String ] ):
  • Header is an optional string array of HTTP headers sent with the request to the server. TargetFile is an optional file to which the response is written. If TargetFile is not specified, the data received from the server is stored in memory. You can access the data using standard stream methods or the Peek method. If TargetFile is specified, the data received from the server is stored in the specified file and is not available in the internal memory buffer afterwards.
  • Put ( ContentType As String, Data As String [ , Headers As String[ ], TargetFile As String ] ):
  • ContentType is the MIME type of the data. Data is the data to be set. Headers is an optional string array of HTTP headers. TargetFile is the path of an optional file to which the response will be written.
  • PostFile ( ContentType As String, Path As String [ , Headers As String[ ], TargetFile As String ] ):
  • ContentType is the MIME type of the file. Path is the path of the file to be sent. Headers is an optional string array of HTTP headers. TargetFile is an optional file to which the response will be written. If TargetFile is not specified, the data received from the server is stored in memory. You can access it using standard stream methods or the Peek method. However, if TargetFile is specified, the data received from the server is stored in the specified file and is not available in the internal memory buffer afterwards.

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:

  • In line 5, the procedure CheckNetwork is used to test whether a network is reachable.
  • The external IP address is displayed in line 9 as the value of the function HTTPGetIP(…).
  • First, a new HTTPClient is created in line 18 in the HTTPGetIP(…) function.
  • The client is then assigned essential properties. The URL of the page to be called up is passed as an argument to the above-mentioned function in line 19.
  • Afterwards, the Async property is set to False, which results in the setting of a timeout → TimeOut property in Table 24.2.4.0.1.
  • Then the data in line 23 is retrieved with the Get() method and stored in memory.
  • Finally, in line 25, the memory is completely read and stored in the function value by the HTTPGetIP(…) function, which is output in line 27.

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

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k24/k24.2/k24.2.4/start.txt · Last modified: 16.08.2022 (external edit)

Page Tools