如何将网页下载到变量?

Maw*_*awg 7 delphi

我不在乎它是字符串,字符串列表,备忘录等...但不是磁盘文件

如何将竞争网页下载到变量中?谢谢

Mar*_*ema 17

使用Indy:

uses IdHTTP;

const
  HTTP_RESPONSE_OK = 200;

function GetPage(aURL: string): string;
var
  Response: TStringStream;
  HTTP: TIdHTTP;
begin
  Result := '';
  Response := TStringStream.Create('');
  try
    HTTP := TIdHTTP.Create(nil);
    try
      HTTP.Get(aURL, Response);
      if HTTP.ResponseCode = HTTP_RESPONSE_OK then begin
        Result := Response.DataString;
      end else begin
        // TODO -cLogging: add some logging
      end;
    finally
      HTTP.Free;
    end;
  finally
    Response.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

  • @MarjanVenema,你有没有理由使用`TStringStream`?为什么不简单:`结果:= HTTP.Get(URL)` (4认同)
  • Indy在这里击败了WinInet,因为WinInet有毛刺,包括恐惧超时错误.如果您需要使用代理做一些非常奇怪的事情,WinInet可以很方便.WinHttp将是另一种选择. (2认同)

And*_*and 14

使用本机Microsoft Windows WinInet API:

function WebGetData(const UserAgent: string; const URL: string): string;
var
  hInet: HINTERNET;
  hURL: HINTERNET;
  Buffer: array[0..1023] of AnsiChar;
  BufferLen: cardinal;
begin
  result := '';
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if hInet = nil then RaiseLastOSError;
  try
    hURL := InternetOpenUrl(hInet, PChar(URL), nil, 0, 0, 0);
    if hURL = nil then RaiseLastOSError;
    try
      repeat
        if not InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen) then
          RaiseLastOSError;
        result := result + UTF8Decode(Copy(Buffer, 1, BufferLen))
      until BufferLen = 0;
    finally
      InternetCloseHandle(hURL);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

试试吧:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Text := WebGetData('My Own Client', 'http://www.bbc.co.uk')
end;
Run Code Online (Sandbox Code Playgroud)

但这仅在编码为UTF-8时有效.因此,要使其在其他情况下工作,您必须单独处理这些,或者您可以使用Mary建议的Indy高级包装器.我承认他们在这种情况下是优越的,但我仍然希望推广基础API,如果没有其他原因而不是教育......