【发布时间】:2019-01-04 17:05:12
【问题描述】:
不管是字符串、字符串列表、备忘录等...但不是磁盘文件
如何将竞争网页下载到变量中?谢谢
【问题讨论】:
标签: delphi
不管是字符串、字符串列表、备忘录等...但不是磁盘文件
如何将竞争网页下载到变量中?谢谢
【问题讨论】:
标签: delphi
使用印地:
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;
【讨论】:
TStringStream 有什么原因吗?为什么不简单:Result := HTTP.Get(URL)
使用本机 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,如果没有其他原因,除了教育......
【讨论】: