TWebClient

Source: source/classes/twebclie.prg

TWebClient is FiveWin's lightweight HTTP client class, built directly on top of TSocket. It provides a simple interface for connecting to web servers, fetching pages, and processing HTTP responses. For more advanced HTTP features (HTTPS, POST with JSON, custom headers), consider using the hb_curl library directly or the TOpenAI/AI classes as reference.

Key DATA Members

DATATypeDescription
oSocketTSocketUnderlying TCP socket for the HTTP connection
bOnConnectBlockCallback executed when the connection to the server is established
bOnReadBlockCallback executed when data arrives from the server

Methods

MethodDescription
New()Create a new TWebClient. Creates and configures the underlying TSocket with default read/connect/close handlers.
Connect( cIPAddress )Connect to a web server. Accepts hostname (e.g. "example.com") or IP address. Resolves hostnames automatically.
GetPage( cPageName )Send an HTTP GET request for the specified page path. Supports both full URLs (http://...) and relative paths.
OnConnect()Called internally when the connection is established. Triggers the bOnConnect callback if set.
OnRead( cData )Called internally when data is received. Triggers the bOnRead callback with the received data.

Example: Fetch a Web Page

#include "FiveWin.ch"

function Main()

   local oClient, cResponse := ""

   oClient := TWebClient():New()

   oClient:bOnConnect := { ||
      oClient:GetPage( "/" )
   }

   oClient:bOnRead := { |cData|
      cResponse += cData
   }

   oClient:Connect( "www.example.com" )

   // Wait for response
   SysRefresh()
   Inkey( 3 )

   // Display the HTTP response
   ? "Response received:", Len( cResponse ), "bytes"
   ? SubStr( cResponse, 1, 500 )

return nil

Example: REST API Call

#include "FiveWin.ch"

function Main()

   local oClient, cResponse := ""
   local cApiHost := "api.github.com"
   local cEndpoint := "/repos/FiveTechSoft/FWH"

   oClient := TWebClient():New()

   oClient:bOnConnect := { ||
      // Send a GET request to the GitHub API
      oClient:GetPage( cEndpoint + ;
        " HTTP/1.1" + CRLF + ;
        "Host: " + cApiHost + CRLF + ;
        "User-Agent: FWH-WebClient" + CRLF + ;
        "Accept: application/vnd.github.v3+json" + CRLF + ;
        "Connection: close" )
   }

   oClient:bOnRead := { |cData|
      cResponse += cData
   }

   oClient:Connect( cApiHost )

   // Wait for the async operation
   SysRefresh()
   Inkey( 5 )

   // Display the response
   if ! Empty( cResponse )
      MemoWrit( "github_response.txt", cResponse )
      ? "Response saved to github_response.txt"
   endif

return nil

Notes

See Also