Delphi TIdHTTP POST is very slow vs GET

2019-05-30 21:56发布

Delphi 2009

I recently switched from multiple GET requests to a single POST which I thought would be more efficient but it has turned out to be much slower. It went from 1-2 seconds to 8-10 seconds and I can't figure out why.

example

unit Unit4;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
  IdHTTP;

type
  TForm4 = class(TForm)
    d: TIdHTTP;
    Memo1: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

procedure TForm4.Button1Click(Sender: TObject);
var m: tmemorystream;
    data: tstringlist;
    i: integer;
begin
  memo1.Clear;

  m:=tmemorystream.Create;
  data:=tstringlist.Create;
  data.Add(format('test1');
  data.Add(format('test2');

  d.Post('http://www.someurl.com/test.php', data, m);
  m.Position:=0;
  data.LoadFromStream(m);
  memo1.Lines.Add('Received:');

  for i := 0 to data.count - 1 do
    memo1.Lines.Add(data[i]);

  m.Free;
  data.Free;
end;

end.

and on the server

<?php
echo "1\n";
?>

标签: delphi http indy
2条回答
霸刀☆藐视天下
2楼-- · 2019-05-30 22:32

I did a simple test using different urls:

d.Post('http://whatismyip.org', data, m); // Using DNS name

or

d.Post('http://54.242.203.46', data, m); // Using IP

The Post took ~1 sec, so I think your problem may not be connected with Indy. My suggestions:

  • Check PC's DNS resolving. Try using IP address to see if there is difference;
  • Try issuing POST request to the same site using external tools (curl, vbscript etc.) and measure the time ;
  • Use Network monitoring tools (Wireshark, MS Network Monitor etc.) to see how long it takes for the server to respond to your POST request or how much time the client spends between resolving address and the actual Post request.

These steps can narrow where the problem is.

If none of these help - try upgrading Indy to the latest version.

查看更多
叼着烟拽天下
3楼-- · 2019-05-30 22:34

Make sure the hoKeepOriginalProtocol flag is enabled in the TIdHTTP.HTTPOptions property. By default, TIdHTTP.Post() forces the connection to be closed each time it is called, regardless of the use of HTTP keep-alives, unless that flag is enabled. The added overhead of disconnecting and reconnecting might account for the extra time.

查看更多
登录 后发表回答