Search code examples
delphihttpshttp-postindy

How to set body data indy HTTPS post


So I've looked around, and the only question describing my problem is 6 years old with 0 answers, so I guess I will try again.

I am using delphi 2009 with Indy10.

I am trying to post JSON to an api using HTTPS.

Instance.FHTTP := TIdHTTP.Create;
Instance.FHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(Instance.FHTTP);

{$IFDEF DEBUG}
Instance.FHTTP.ProxyParams.ProxyPort := 8888;
Instance.FHTTP.ProxyParams.ProxyServer := '127.0.0.1';
{$ENDIF}

Instance.FHTTP.Request.ContentType := 'application/json';
Instance.FAccessToken := Instance.FHTTP.Post('https://somedomain.com/api/endpoint', '{JSONName: JSONValue }' );

I have seen many answers suggesting that the JSON payload should be given as a string param in the TidHTTP.Postmethod, but when i try that, it expects a filepath, and throws an error saying:

'Cannot open file "[path to project{JSONName:JSONValue }]". The specified file was not found'.

If i add my JSON to a TStringList and add give that as a parameter, it simply adds the JSON to the header of the request.

Any help is greatly appreciated.


Solution

  • The Post overload that takes a second string indeed interprets it as a filename:

    function Post(AURL: string; const ASourceFile: String): string; overload;
    

    That's why this doesn't work. You need to instead use the overload that takes a TStream:

    function Post(AURL: string; ASource: TStream): string; overload;
    

    You can put your JSON in a TStringStream:

    StringStream := TStringStream.Create('{JSONName: JSONValue }', TEncoding.UTF8);
    try
      Instance.FAccessToken := Instance.FHTTP.Post('https://somedomain.com/api/endpoint', StringStream);
    finally
      StringStream.Free;
    end;