通过Delphi引用WinHTTP.dll

时间:2011-05-23 15:43:18

标签: delphi http com activex

自从我第一次启动Delphi以来,我一直想知道如何使用HTTP请求。 我不想使用任何替代HTTP库,因为我习惯使用WinHTTP(DLL,而不是lib)。

那么有人可以尝试向我解释如何通过Delphi引用/使用它吗? 在Visual Basic.NET中,您所要做的就是从调色板中选择组件。

2 个答案:

答案 0 :(得分:4)

我写了一个WinHttp.dll和WinINet.dll的端口。

查看SynCrtSock.pas中定义的TWinHttpTWinINet个类。它们允许直接访问这些库

以下是TWinHTTP使用的低级转换:

{ TWinHTTP }

const
  winhttpdll = 'winhttp.dll';

  WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0;
  WINHTTP_FLAG_REFRESH = $00000100;
  WINHTTP_FLAG_SECURE = $00800000;
  WINHTTP_ADDREQ_FLAG_COALESCE = $40000000;
  WINHTTP_QUERY_FLAG_NUMBER = $20000000;

function WinHttpOpen(pwszUserAgent: PWideChar; dwAccessType: DWORD;
  pwszProxyName, pwszProxyBypass: PWideChar; dwFlags: DWORD): HINTERNET; stdcall; external winhttpdll;
function WinHttpConnect(hSession: HINTERNET; pswzServerName: PWideChar;
  nServerPort: INTERNET_PORT; dwReserved: DWORD): HINTERNET; stdcall; external winhttpdll;
function WinHttpOpenRequest(hConnect: HINTERNET; pwszVerb: PWideChar;
  pwszObjectName: PWideChar; pwszVersion: PWideChar; pwszReferer: PWideChar;
  ppwszAcceptTypes: PLPWSTR; dwFlags: DWORD): HINTERNET; stdcall; external winhttpdll;
function WinHttpCloseHandle(hInternet: HINTERNET): BOOL; stdcall; external winhttpdll;
function WinHttpAddRequestHeaders(hRequest: HINTERNET; pwszHeaders: PWideChar; dwHeadersLength: DWORD;
  dwModifiers: DWORD): BOOL; stdcall; external winhttpdll;
function WinHttpSendRequest(hRequest: HINTERNET; pwszHeaders: PWideChar;
  dwHeadersLength: DWORD; lpOptional: Pointer; dwOptionalLength: DWORD; dwTotalLength: DWORD;
  dwContext: DWORD): BOOL; stdcall; external winhttpdll;
function WinHttpReceiveResponse(hRequest: HINTERNET;
  lpReserved: Pointer): BOOL; stdcall; external winhttpdll;
function WinHttpQueryHeaders(hRequest: HINTERNET; dwInfoLevel: DWORD; pwszName: PWideChar;
  lpBuffer: Pointer; var lpdwBufferLength, lpdwIndex: DWORD): BOOL; stdcall; external winhttpdll;
function WinHttpReadData(hRequest: HINTERNET; lpBuffer: Pointer;
  dwNumberOfBytesToRead: DWORD; var lpdwNumberOfBytesRead: DWORD): BOOL; stdcall; external winhttpdll;

在同一个单元中,您还使用快速 http.sys 内核模式服务器实现HTTP服务器的THttpApiServer类。

从我的测试中,我发现TWinHttp / THttpApiServer类是更快的HTTP解决方案,其开销远低于Indy或Synapse组件,并且具有一些很好的功能,如本机HTTPS。

对于那些不知道WinHttp.dll的人来说,它比WinINet.dll快得多(可能会死得很慢)。因此,TWinHttp TWinINet更快,并且与 WinSocks 的低级别直接调用一样快。

答案 1 :(得分:1)

您可以在Delphi代码中使用任何DLL的导出函数。例如,这是您使用WinHttpConnect函数的方式:

unit Unit1;

interface

uses WinInet;

...

function WinHttpConnect(hSession: HINTERNET; pswzServerName: PChar;
  nServerPort: INTERNET_PORT; dwReserved: cardinal): HINTERNET; stdcall;

...

implementation

...

function WinHttpConnect; external 'Winhttp.dll' name 'WinHttpConnect';

...

您甚至不需要添加uses WinInet。如果你不这样做,你需要知道

type
  HINTERNET = pointer;
  INTERNET_PORT = word;