I’m using the IGN REST API to get ground elevation at geographic coordinates:
RESTClient.BaseURL := https://wxs.ign.fr/calcul/alti/rest
procedure TAffiche.Button1Click(Sender: TObject);
var
PointLong : string;
PointLat : string;
JsonValue : TJSONValue;
Elevation : string;
Resource : string;
begin
if not DetectionConnexion then
begin
raise Exception.Create('Internet connection not availlable.');
end
else
begin
try
MemoData.Clear;
PointLong := LongRef;
PointLat := LatRef;
Resource := 'elevation.json?lon=' + PointLong + '&lat=' + PointLat + '&indent=true';
RESTRequest1.Resource := Resource;
RESTRequest1.Execute;
JsonValue := RESTResponse1.JSONValue;
Elevation := JsonValue.GetValue<string>('elevations[0].z');
finally
JSONValue.Free;
RESTClient1.Free;
RESTRequest1.Free;
// RestResponse1.Free;
end;
end;
end;
The code works fine on the first click of the button. But when I click a second time, an error occurs:
RestRequest1.Resource : Access violation
I tried to free memory with RESTResponse1.Free
, but the same error occurs.
When I exit the program, the same error occurs.
I can’t figure out what the issue is.
2
The problem lies in you freeing and thus destroying the RESTRequest1
and RESTClient1
from within your button OnClick
event method. So, when you click your button again they no longer exist, hence why you get an Access Violation exception.
Now, based on their naming, I’m guessing these are actually components that you have placed on your Form at design-time. If so, then the form is their owner and will take care of their destruction when it gets destroyed.
You may also want to check REST.Client.TCustomRESTRequest.ResetToDefaults
, which resets both RESTRequest
and RESTResponse
to their default state, so you can make multiple requests one after another without the need of destroying and then recreating the whole RESTRequest
component every time.
1