How to send HTTP data and get response with Synapse (Delphi)

TreantBG picture TreantBG · Jun 9, 2011 · Viewed 14k times · Source

I think the title was clear enough. I want to know how to send HTTP POST request with parameters/arguments and receive HTML response back - using Synapse library for Delphi.

Answer

user532231 picture user532231 · Jun 9, 2011

Try to use HttpPostURL function.

function HttpPostURL(const URL, URLData: string; const Data: TStream): Boolean;

URL - target URL
URLData - URL parameters; must be encoded e.g. using EncodeURLElement function
Data - target stream, where the response will be stored

The following example uses testing POST server where send two POST parameters. Note using of EncodeURLElement function for encoding parameter data. If the POST succeed the server response is saved into the file.

uses HTTPSend, Synacode;

procedure TForm1.Button1Click(Sender: TObject);
var URL: string;
    Params: string;
    Response: TMemoryStream;

begin
  Response := TMemoryStream.Create;

  try
    URL := 'http://posttestserver.com/post.php?dump&html';

    Params := 'parameter1=' + EncodeURLElement('data1') + '&' +
              'parameter2=' + EncodeURLElement('data2');

    if HttpPostURL(URL, Params, Response) then
      Response.SaveToFile('c:\response.txt');

  finally
    Response.Free;
  end;
end;