我不在乎它是字符串,字符串列表,备忘录等......但不是磁盘文件
如何将竞争网页下载到变量中?感谢
答案 0 :(得分: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;
答案 1 :(得分: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;
试一试:
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Text := WebGetData('My Own Client', 'http://www.bbc.co.uk')
end;
但这仅在编码为UTF-8时有效。因此,要使其在其他情况下工作,您必须单独处理这些,或者您可以使用Mary建议的Indy高级包装器。我承认他们在这种情况下是优越的,但我仍然希望推广基础API,如果没有其他原因而不是教育......