Delphi 通過URL地址獲取網頁源碼的方法


Delphi 通過URL地址獲取網頁源碼的方法

uses WinInet, Classes, Windows;

function UrlGetStr(const URL: string; ShowHeaders: boolean = false): string;
const
  Agent = 'Internet Explorer 6.0';
var
  hFile, HInet: HINTERNET;
  Buffer: array[0..32767] of Char;
  BufRead: Cardinal;
  BufSize: Cardinal;
  TempStream: TStringStream;
  dwIndex: dword;
begin
  HInet := InternetOpen(PChar(Agent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(HInet) then
  try
    hFile := InternetOpenUrl(HInet, PChar(URL), nil, 0, 0, 0);

    TempStream := TStringStream.Create('');

    dwIndex := 0;
    BufSize := SizeOf(Buffer);

    HttpQueryInfo(hfile, HTTP_QUERY_RAW_HEADERS_CRLF, @Buffer, BufSize, dwIndex);

    if ShowHeaders then TempStream.Write(Buffer, BufSize);

    if Assigned(hFile) then
    try
      with TempStream do
      try
        while InternetReadFile(hFile, @Buffer, BufSize, BufRead) and (BufRead > 0) do
          Write(Buffer, BufRead);
        Result := DataString;
      finally
        Free;
      end;
    finally
      InternetCloseHandle(hFile);
    end;
  finally
    InternetCloseHandle(hinet);
  end;
end;

  

 

 

 

創建時間:2020.11.23  更新時間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM