Search code examples
httpdelphiindyidhttp

How to send content with TIdHttp GET request?


I am trying to access a REST server that has an endpoint that uses the GET verb while it also requires json data to be sent in the body

I am trying to accomplish that with an TIdHttp class, using the Get method.

Right now I create a TStringStream with the json data, and then assign that stream to the Request.Source property of the TIdHttp object.

The server however responds with an error code indicating it did not receive the body.

How do you send a body with GET request using TIdHttp?


Solution

  • Assigning the TIdHTTP.Request.Source property will not work because the Source will get replaced with nil when TIdHTTP.Get() calls TIdHTTP.DoRequest() internally passing nil for its ASource parameter.

    So, to do what you are asking, you will have to call DoRequest() directly. However, it is a protected method, so you will have to use an accessor class to reach it.

    For example:

    type
      TIdHTTPAccess = class(TIdHTTP)
      end;
    
    var
      QueryData, ReplyData: TStream;
    begin
      QueryData := TStringStream.Create('... json data here...', TEncoding.UTF8);
      try
        IdHTTP1.Request.ContentType := 'application/json';
        IdHTTP1.Request.CharSet := 'utf-8';
    
        //Result := IdHTTP1.Get('http://...');
        ReplyData := TMemoryStream.Create;
        try
          TIdHTTPAccess(IdHTTP1).DoRequest(Id_HTTPMethodGet, 'http://...', QueryData, ReplyData, []);
          ReplyData.Position := 0;
          Result := ReadStringAsCharset(ReplyData, IdHTTP1.Response.Charset);
        finally
          ReplyData.Free;
        end;
      finally
        QueryData.Free;
      end;
    end;