我想在我的应用程序中调用一个web服务,我可以在导入WSDL时使用它,或者在URL和参数中使用"HTTP“,所以我更喜欢后者,因为它很简单。
我知道我可以使用indy idhttp.get来完成这项工作,但是这是非常简单的事情,我不想在我的应用程序中添加复杂的indy代码。
UPDATE:对不起,如果我不清楚的话,我的意思是“不添加复杂的indy代码”,我不希望只为这个简单的任务添加indy组件,而更倾向于使用更轻松的方式。
发布于 2008-11-19 11:27:46
您可以像这样使用WinINet API:
uses WinInet;
function GetUrlContent(const Url: string): string;
var
NetHandle: HINTERNET;
UrlHandle: HINTERNET;
Buffer: array[0..1024] of Char;
BytesRead: dWord;
begin
Result := '';
NetHandle := InternetOpen('Delphi 5.x', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(NetHandle) then
begin
UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
if Assigned(UrlHandle) then
{ UrlHandle valid? Proceed with download }
begin
FillChar(Buffer, SizeOf(Buffer), 0);
repeat
Result := Result + Buffer;
FillChar(Buffer, SizeOf(Buffer), 0);
InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
until BytesRead = 0;
InternetCloseHandle(UrlHandle);
end
else
{ UrlHandle is not valid. Raise an exception. }
raise Exception.CreateFmt('Cannot open URL %s', [Url]);
InternetCloseHandle(NetHandle);
end
else
{ NetHandle is not valid. Raise an exception }
raise Exception.Create('Unable to initialize Wininet');
end;
来源:http://www.scalabium.com/faq/dct0080.htm
WinINet API使用InternetExplorer使用的相同内容,因此您也可以免费获得InternetExplorer设置的任何连接和代理设置。
发布于 2008-11-19 11:13:15
使用Indy调用RESTful web服务是非常直接的。
将IdHTTP添加到uses子句中。请记住,IdHTTP需要URL上的"HTTP://“前缀。
function GetURLAsString(const aURL: string): string;
var
lHTTP: TIdHTTP;
begin
lHTTP := TIdHTTP.Create;
try
Result := lHTTP.Get(aURL);
finally
lHTTP.Free;
end;
end;
发布于 2011-10-13 20:17:29
实际上,接受答案中的代码对我不起作用。所以我对它做了一些修改,这样它实际上返回了字符串,并在执行后优雅地关闭了所有内容。示例以UTF8String的形式返回检索到的数据,因此它在ASCII和UTF8页面上都能很好地工作。
uses WinInet;
function GetUrlContent(const Url: string): UTF8String;
var
NetHandle: HINTERNET;
UrlHandle: HINTERNET;
Buffer: array[0..1023] of byte;
BytesRead: dWord;
StrBuffer: UTF8String;
begin
Result := '';
NetHandle := InternetOpen('Delphi 2009', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if Assigned(NetHandle) then
try
UrlHandle := InternetOpenUrl(NetHandle, PChar(Url), nil, 0, INTERNET_FLAG_RELOAD, 0);
if Assigned(UrlHandle) then
try
repeat
InternetReadFile(UrlHandle, @Buffer, SizeOf(Buffer), BytesRead);
SetString(StrBuffer, PAnsiChar(@Buffer[0]), BytesRead);
Result := Result + StrBuffer;
until BytesRead = 0;
finally
InternetCloseHandle(UrlHandle);
end
else
raise Exception.CreateFmt('Cannot open URL %s', [Url]);
finally
InternetCloseHandle(NetHandle);
end
else
raise Exception.Create('Unable to initialize Wininet');
end;
希望它能帮助像我这样的人寻找简单的代码,如何在Delphi中检索页面内容。干杯,阿尔迪斯:)
https://stackoverflow.com/questions/301546
复制相似问题