Brian Cryer

 

Cry about...
Delphi Programming with WinInet


InternetOpenUrl and HttpQueryInfo Example

How to determine if a URL is valid using HttpQueryInfo


The following code fragment shows how to use InternetOpenUrl and HttpQueryInfo to determine if a URL (i.e. a website address) is valid. It requires a connection to the internet.

function IsUrlValid(const url: string): boolean;
var
  hInet: HINTERNET;
  hConnect: HINTERNET;
  infoBuffer: array [0..512] of char;
  dummy: DWORD;
  bufLen: DWORD;
  okay: LongBool;
  reply: String;
begin
  hInet := InternetOpen(PChar(application.title),
    INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY,nil,nil,0);
  hConnect := InternetOpenUrl(hInet,PChar(url),nil,0,
    INTERNET_FLAG_NO_UI,0);
  if not Assigned(hConnect) then
    //----------------------------------------------------------
    // If we couldn't open a connection then we know the url
    // is bad. The most likely reason is that the url is bad,
    // but it could be because of an unknown or badly specified
    // protocol.
    //----------------------------------------------------------
    result := false
  else
  begin
    //------------------------------
    // Create a request for the url.
    //------------------------------
    dummy := 0;
    bufLen := Length(infoBuffer);
    okay := HttpQueryInfo(hConnect,HTTP_QUERY_STATUS_CODE,
      @infoBuffer[0],bufLen,dummy);
    if not okay then
      // Probably working offline, or no internet connection.
      result := False
    else
    begin
      reply := infoBuffer;
      if reply = '200' then
        // File exists, all ok.
        result := True
      else if reply = '401' then
        // Not authorised. Assume page exists,
        // but we can't check it.
        result := True
      else if reply = '404' then
        // No such file.
        result := False
      else if reply = '500' then
        // Internal server error.
        result := False
      else
        // Shouldn't get here! It means there is
        // a status code left unhandled.
        result := False;
    end;
    InternetCloseHandle(hConnect);
  end;
  InternetCloseHandle(hInet);
end;

Note:

  • If you want to make use of this function in your application, then be aware that InternetOpen need only be called once in your application. The call to InternetOpen is only included in the above to give a self contained example.

These notes are believed to be correct for Delphi 6 and Delphi 7 and may apply to other versions as well.



About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.