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  更新时间

posted on 2020-11-23 11:05  滔Roy  阅读(987)  评论(0编辑  收藏  举报

导航