I'm working on a DElphi FMX project where I make a lot of requests to a REST backend.
I'm using one TRESTClient, and are dynamically creting a TRESTRequest every time I ask for something, my plan is to make it multitreading to make the UI be more responsive.
I have made a function called DoRequest, that do the actual request, it looks like something this:
Function TFormMain.Dorequest(Meth:TRESTRequestmethod;Url,RequestBody:String;
Var Respons: TCustomRESTResponse):Boolean;
Var
par: TRESTRequestParameter;
Req : TRESTRequest;
begin
Req := TRESTRequest.Create(RESTClient);
With Req do
try
if RequestBody<>'' then
begin
Params.Clear;
par := Params.AddItem('body',RequestBody);
par.ContentType := ctAPPLICATION_JSON;
par.Kind := pkREQUESTBODY;
end;
Method := Meth;
Resource := Url;
Execute;
Respons := Response;
Result := Respons.StatusCode In [200,201];
finally
Req.Free; // <-Error here
end;
end;
I call it like this:
procedure TFormUser.Button1Click(Sender: TObject);
Var
Respons: TCustomRESTResponse;
begin
If DoRequest(rmPOST,CreateUserUrl,JSON,Respons) then
begin
ShowMessage('User '+EdEmail.Text+' created');
ModalResult := MrOk;
end
However, I get an Acces Violation when freeing Req, my TRESTRequest.
I found out that it is because the TCustomRESTResponse Respons is just made a pointer to the memory where the Req.Response is placed, so freeing Req also destroys Respons.
My question is: How do I make a copy of Req.Response that lives after Req is freed?
I have tried Respons.Assign(Response), but it gives the rather strange error: "Cannot assign a TCustomRESTResponse to a TFormMain"
Am I doing this the wrong way, also keeping in mind that I would like the actual request to be in another tread?
Michael