Getting the headers for an URL

pritaeas 1 Tallied Votes 353 Views Share

This snippet shows how you can get the headers for an URL, for example to detect a redirect. I had to use the ANSI functions to ensure correctly returned headers.

Manual entry for HttpQueryInfo.

Let me know if you have any questions/remarks.

var
  hHttp, hInet, hRequest: HINTERNET;
  infoBuffer: array [0..8191] of AnsiChar;
  dummy: DWORD;
  bufLen: DWORD;
  url, info: Ansistring;
begin
  hInet := InternetOpenA(PAnsiChar(AGENT), INTERNET_OPEN_TYPE_PRECONFIG, nil,
    nil, 0);

  hHttp := InternetConnectA(hInet, PAnsiChar(SERVER), 
    INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);

  url := 'http://pritaeas.net/'; // this redirects to www.pritaeas.net

  hRequest := InternetOpenUrlA(hInet, PAnsiChar(url), nil, 0,
    INTERNET_FLAG_NO_UI or INTERNET_FLAG_NO_AUTO_REDIRECT or
    INTERNET_FLAG_NO_COOKIES, 0);

  dummy := 0;
  bufLen := Length(infoBuffer);

  // HTTP_QUERY_LOCATION     gets only the redirect location, if any
  // HTTP_QUERY_STATUS_CODE  gets only the HTTP status code

  HttpQueryInfoA(hRequest, HTTP_QUERY_RAW_HEADERS_CRLF, 
    @infoBuffer[0], bufLen, dummy);

  info := infoBuffer;
  ShowMessage(info);

  InternetCloseHandle(hRequest);
  InternetCloseHandle(hHttp);
  InternetCloseHandle(hInet);
end;
vrkiro 0 Newbie Poster

Nice :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.