【问题标题】:How to download a web page into a variable?如何将网页下载到变量中?
【发布时间】:2019-01-04 17:05:12
【问题描述】:

不管是字符串、字符串列表、备忘录等...但不是磁盘文件

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

【问题讨论】:

标签: delphi


【解决方案1】:

使用印地:

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;

【讨论】:

  • +1 但是,我在“使用”中需要什么才能获得 HTTP_RESPONSE_OK ?
  • @MarjanVenema,您使用TStringStream 有什么原因吗?为什么不简单:Result := HTTP.Get(URL)
  • @kobik:哦,那只是因为它是实际代码的剥离版本,在该代码中我使用流来查找特定内容。
  • @Mawg:抱歉,这是我自己的常数之一。它的值为 200(整数)。用它更新答案。
  • Indy 在这里击败了 WinInet,因为 WinInet 存在故障,包括可怕的超时错误。如果您需要使用代理做一些非常奇怪的事情,WinInet 会很方便。 WinHttp 将是另一种选择。
【解决方案2】:

使用本机 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;

试试看:

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

但这仅适用于编码为 UTF-8 的情况。因此,要使其在其他情况下工作,您必须单独处理这些,或者您可以使用 Indy 高级包装器,如 Marjan 所建议的那样。我承认他们在这种情况下更胜一筹,但我仍然想推广底层 API,如果没有其他原因,除了教育......

【讨论】:

  • 大声笑,抱歉,已更正。我的大脑开始起雾了。一定是因为我上周四过了 50 岁。
猜你喜欢
  • 2023-04-04
  • 2010-10-30
  • 1970-01-01
  • 2017-06-29
  • 2015-10-09
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多