深圳全飞鸿
标题:
delphi通过api获得网页代码, getWebPae
[打印本页]
作者:
admin
时间:
2019-7-25 22:17
标题:
delphi通过api获得网页代码, getWebPae
uses WinInet;
function TForm1.getWebPage(url: string): string;
var
Session,
HttpFile:HINTERNET;
szSizeBuffer:Pointer;
dwLengthSizeBuffer:DWord;
dwReserved:DWord;
dwFileSize:DWord;
dwBytesRead:DWord;
Contents:PChar;
begin
Session:=InternetOpen('',0,niL,niL,0);
HttpFile:=InternetOpenUrl(Session,PChar(Url),niL,0,0,0);
dwLengthSizeBuffer:=1024;
HttpQueryInfo(HttpFile,5,szSizeBuffer,dwLengthSizeBuffer,dwReserved);
GetMem(Contents,dwFileSize);
ZeroMemory(Contents,dwFileSize); //fix by syant -- win10下可能有垃圾数据
InternetReadFile(HttpFile,Contents,dwFileSize,dwBytesRead);
InternetCloseHandle(HttpFile);
InternetCloseHandle(Session);
Result:=StrPas(Contents);
FreeMem(Contents);
end;
复制代码
而后在crc_notice中的实现是:
begin
try
Session:=InternetOpen('',0,niL,niL,0);
HttpFile:=InternetOpenUrl(Session,PChar(Url),niL,0,INTERNET_FLAG_RELOAD,0);
//dwLengthSizeBuffer:=sizeof(Buffer);
//HttpQueryInfo(HttpFile,HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER,@Buffer,dwLengthSizeBuffer,dwReserved);
dwFileSize:=1024;
GetMem(Contents,dwFileSize);
ZeroMemory(Contents, dwFileSize);
InternetReadFile(HttpFile,Contents,dwFileSize,dwBytesRead);
InternetCloseHandle(HttpFile);
InternetCloseHandle(Session);
Result:=StrPas(Contents);
if((length(result)>dwBytesRead) and (dwBytesRead>0))then result:=copy(result,1,dwBytesRead);
FreeMem(Contents);
except
result:='00';
end;
复制代码
不知道为什么不能获得文件大小!
最后的解决方案:
function TForm1.UrlGetStr(const URL: string): 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;
复制代码
结论:都是没有内存泄漏,都是用时0~16毫秒!
欢迎光临 深圳全飞鸿 (http://www.nagomes.com/disc/)
Powered by Discuz! X3.2