cyberdude cyberdude - 3 months ago 93
HTTP Question

how to use HTTP Client API in Delphi xe

How to use NetHTTPClient instead of idHTTP, there are few resources on the internet showing how to use HTTP Client API, i couldn't fit it in my code, any help guys, thanks

what i have tried :

var
LHTTPClient: THTTPClient;
P : TStrings;
begin
LHTTPClient := THTTPClient.Create;
P := TStringList.Create;
try
Params.Add('test=' + Path);
Memo1.Lines.Text := NetHTTPClient1.Post('www.server.com', P).ContentAsString();
finally
LHTTPClient.Free;
end;
end;


my code :

procedure TForm1.Start;
var
lHTTP: TIdHTTP;
P: TStringList;

begin
lHTTP := TIdHTTP.Create(nil);
P := TStringList.Create;
try
Params.Add('test=' + Path);
try
Reply.Text := lHTTP.Post('www.server.com', P);

if AnsiContainsStr(Reply.Text, 'good')
then
begin
Memo1.Lines.Add(Path);
end;

Finally
end;

end;
end.

Answer

Neither one of your examples is technically correct. Your URLs are incomplete, and you are mismanaging your variable names.

Try this instead:

Indy:

procedure TForm1.Start;
var
  LHTTP: TIdHTTP;
  Params: TStringList;
begin
  LHTTP := TIdHTTP.Create;
  try
    Params := TStringList.Create;
    try
      Params.Add('test=' + Path);
      Memo1.Lines.Text := LHTTP.Post('http://www.server.com', Params);
    finally
      Params.Free;
    end;
  finally
    LHTTP.Free;
  end;
end.

NetHTTP:

procedure TForm1.Start;
var
  LHTTP: TNetHTTPClient;
  Params: TStringList;
begin
  LHTTP := TNetHTTPClient.Create(nil);
  try
    Params := TStringList.Create;
    try
      Params.Add('test=' + Path);
      Memo1.Lines.Text := LHTTP.Post('http://www.server.com', Params).ContentAsString;
    finally
      Params.Free;
    end;
  finally
    LHTTP.Free;
  end;
end;
Comments