Sparkle HTTP Client - Connect through proxy server

Not a support request - I recently had to use the Sparkle HTTP client in my application to connect through a proxy server, without relying on the internet options settings of the current logged in user.  Thought it would be useful to post the code here :



uses
  Sparkle.Http.Client, Sparkle.WinHttp.Engine, Sparkle.WinHttp.Api;


type
  TInternalHTTPClient = class(THttpClient);
 
...
 
var
  httpClient: THttpClient;
  httpEngine: TWinHttpEngine;
  httpRequest: THttpRequest;
  httpResponse: THttpResponse;
  proxyInfo: WINHTTP_PROXY_INFO;
  blnUseProxyServer: Boolean;
  sProxyServerHostAddress, sProxyServerUsername, sProxyServerPassword: string;
  intProxyServerPort: Integer;
begin
  // Sample proxy server settings
  blnUseProxyServer := True;
  sProxyServerHostAddress := 'localhost';
  intProxyServerPort := 8080;
  sProxyServerUsername := 'proxyuser';
  sProxyServerPassword := 'proxypass';


  httpClient := THttpClient.Create;
  
  // Setup HTTP request properties
  httpRequest := httpClient.CreateRequest;
  ...
  
  if (blnUseProxyServer = True) then
  begin
    // Configure proxy server host and port
    proxyInfo.dwAccessType := WINHTTP_ACCESS_TYPE_NAMED_PROXY;
    proxyInfo.lpszProxy := PWideChar(sProxyServerHostAddress + ':' + IntToStr(intProxyServerPort));


    // Use 'BeforeWinHttpSendRequest' event to set proxy server configuration
    httpEngine := TWinHttpEngine(TInternalHTTPClient(httpClient).Engine);
    httpEngine.BeforeWinHttpSendRequest :=
      procedure (Req: HINTERNET)
      begin
        // Set proxy server host address & port
        WinHttpCheck(WinHttpSetOption(Req, WINHTTP_OPTION_PROXY, @proxyInfo, SizeOf(proxyInfo)));


        // Set the proxy server username & password (only applies if proxy username is not blank)
        if (sProxyServerUsername <> '') then
          WinHttpCheck(WinHttpSetCredentials(Req, WINHTTP_AUTH_TARGET_PROXY, WINHTTP_AUTH_SCHEME_BASIC, PWideChar(sProxyServerUsername), PWideChar(sProxyServerPassword), nil));
      end;
  end;
 
  // Execute HTTP request
  httpResponse := httpClient.Send(httpRequest);
 

Jonathan

Thank you Jonathan. It will for sure be useful for other users.