【问题标题】:How to send a HTTP Post Request in Delphi 2010 using WinInet [duplicate]如何使用 WinInet 在 Delphi 2010 中发送 HTTP Post 请求 [重复]
【发布时间】:2011-02-27 23:53:00
【问题描述】:

我想在 Delphi 2010 中使用 WinInet 发送 HTTP Post 请求,但我的脚本不起作用;/

这是我的 Delphi 脚本:

uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
var
  hNet,hURL,hRequest: HINTERNET;
begin
  hNet := InternetOpen(PChar('User Agent'),INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if Assigned(hNet) then
  begin
  try
    hURL := InternetConnect(hNet,PChar('http://localhost/delphitest.php'),INTERNET_DEFAULT_HTTP_PORT,nil,nil,INTERNET_SERVICE_HTTP,0,DWORD(0));
    if(hURL<>nil) then
      hRequest := HttpOpenRequest(hURL, 'POST', PChar('test=test'),'HTTP/1.0',PChar(''), nil, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE,0);
    if(hRequest<>nil) then
      HttpSendRequest(hRequest, nil, 0, nil, 0);
    InternetCloseHandle(hNet);
  except
      ShowMessage('error');
    end
  end;
end;

还有我的 PHP 脚本:

$data = $_POST['test'];
$file = "test.txt";
$fp = fopen($file, "a");
flock($fp, 2);
fwrite($fp, $data);
flock($fp, 3);
fclose($fp);

【问题讨论】:

  • 请通过将所有行缩进 4 个空格来格式化您的代码。然后会应用语法高亮。
  • 有时自己做会更容易。您也可以编辑问题。
  • 哦,我的错误,但没有这个它仍然无法工作

标签: delphi http post wininet


【解决方案1】:

主要问题:

  • InternetConnect 的第二个参数应该只包含服务器的名称,而不是服务器端脚本的整个 URL。

  • HttpOpenRequest的第三个参数应该是脚本的文件名(URL),而不是POST数据!

  • 实际的POST数据应该是HttpSendRequest的第四个参数。

小问题

  • INTERNET_OPEN_TYPE_PRECONFIG or INTERNET_OPEN_TYPE_PRECONFIGINTERNET_OPEN_TYPE_PRECONFIG就够了。

  • DWORD(0) 太过分了。 0 就够了。

示例代码

我使用以下代码发布数据:

procedure WebPostData(const UserAgent: string; const Server: string; const Resource: string; const Data: AnsiString); overload;
var
  hInet: HINTERNET;
  hHTTP: HINTERNET;
  hReq: HINTERNET;
const
  accept: packed array[0..1] of LPWSTR = (PChar('*/*'), nil);
  header: string = 'Content-Type: application/x-www-form-urlencoded';
begin
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  try
    hHTTP := InternetConnect(hInet, PChar(Server), INTERNET_DEFAULT_HTTP_PORT, nil, nil, INTERNET_SERVICE_HTTP, 0, 1);
    try
      hReq := HttpOpenRequest(hHTTP, PChar('POST'), PChar(Resource), nil, nil, @accept, 0, 1);
      try
        if not HttpSendRequest(hReq, PChar(header), length(header), PChar(Data), length(Data)) then
          raise Exception.Create('HttpOpenRequest failed. ' + SysErrorMessage(GetLastError));
      finally
        InternetCloseHandle(hReq);
      end;
    finally
      InternetCloseHandle(hHTTP);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;

例如:

WebPostData('My UserAgent', 'www.rejbrand.se', 'mydir/myscript.asp', 'value=5');

更新以响应 OP 的回答

要从 Internet 读取数据,请使用 InternetReadFile 函数。我使用下面的代码从网上读取一个小的(单行)文本文件:

function WebGetData(const UserAgent: string; const Server: string; const Resource: string): string;
var
  hInet: HINTERNET;
  hURL: HINTERNET;
  Buffer: array[0..1023] of AnsiChar;
  i, BufferLen: cardinal;
begin
  result := '';
  hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  try
    hURL := InternetOpenUrl(hInet, PChar('http://' + Server + Resource), nil, 0, 0, 0);
    try
      repeat
        InternetReadFile(hURL, @Buffer, SizeOf(Buffer), BufferLen);
        if BufferLen = SizeOf(Buffer) then
          result := result + AnsiString(Buffer)
        else if BufferLen > 0 then
          for i := 0 to BufferLen - 1 do
            result := result + Buffer[i];
      until BufferLen = 0;
    finally
      InternetCloseHandle(hURL);
    end;
  finally
    InternetCloseHandle(hInet);
  end;
end;

示例用法:

WebGetData('My UserAgent', 'www.rejbrand.se', '/MyDir/update/ver.txt')

因此,此函数仅读取数据,没有事先 POST。但是,InternetReadFile 函数也可以与HttpOpenRequest 创建的句柄一起使用,因此它也适用于您的情况。您确实知道 WinInet 参考是 MSDN,对吗?那里详细描述了所有 Windows API 函数,例如 InternetReadFile

【讨论】:

  • 谢谢,我已经合并了这些脚本,现在脚本看起来像这样:paste.org/pastebin/view/19370 按预期工作。再次感谢。
  • @noxwow "Check" 似乎不是一个很好的方法名称。
  • 我正在使用 turbo delphi,它说:[Pascal Fehler] uHTTP.pas(22): E2010 incompatible types: 'Char' und 'WideChar'.. 如何修复?
  • 在WebPostData中,为什么使用AnsiString而不是String作为参数Data的类型?字符串是 WideString。
  • 还有为什么你使用 AnsiChar 作为缓冲区,这是否意味着响应文本将是 ANSI,而不是 Unicode?​​span>
【解决方案2】:
var
  BufferIn : INTERNET_BUFFERS;
  Buffer: array[0..1024] of Byte;
  FTmp: TSomeStream:
  FURL: string;
  ...
begin
... // Create FTmp, set FUrl, ...

  NetHandle := InternetOpen( 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3',
                          INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);

  UrlHandle := HttpOpenRequest(NetHandle, 'POST', PChar(FURL), nil, nil, nil, INTERNET_FLAG_NO_CACHE_WRITE, 0);

  ... // Check handles, etc
  try
    BufferIn.dwBufferTotal := FTmp.Size;

    if not HttpSendRequestEx(UrlHandle, @BufferIn, nil, 0, 0) then
      raise Exception.CreateFmt('Error on HttpSendRequestEx %d\n', [GetLastError()]);

    size := FTmp.Read(Buffer, 1024);
    InternetWriteFile(UrlHandle, @Buffer, size, BytesWritten);

    while (BytesWritten = size) and (BytesWritten > 0) do
    begin
      size := FTmp.Read(Buffer, 1024);
      InternetWriteFile(UrlHandle, @Buffer, size, BytesWritten);
    end;
  finally
    FTmp.Free;

    InternetCloseHandle(UrlHandle);
    InternetCloseHandle(NetHandle);
  end;

【讨论】:

  • 您使用 Firefox UserAgent 有什么原因吗?
  • 没有。只是我曾经尝试下载 html 页面的问题的遗留问题,在该页面中我收到“使用真正的浏览器”而不是我想要的 html 的消息。
【解决方案3】:

http://www.utilmind.com 上有一个库(称为“Delphi 32 的 HTTPGet 组件”)。它将视觉控件安装到您的组件调色板中。 它完全符合您的要求,因此您可能想看看。

【讨论】:

    猜你喜欢
    • 2010-12-21
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2013-09-25
    • 2016-11-16
    • 1970-01-01
    相关资源
    最近更新 更多