I need to call to an ASP web api and return JSON from delphi 2007. I'm able to do it in RAD Studio XE 5 with TRestClient. I was trying to put it in a dll so that I can call it from my delphi 2007 program. But no success. How can I do this using delphi 2007?
EDIT
Here's what I'm trying to do in delphi xe 5
class function TSampleApp.Hello(AModel: TModel): Integer;
var
aRestClient: TRESTClient;
aRestRequest: TRESTRequest;
aRestResponse: TRESTResponse;
aParam: TRESTRequestParameter;
jValue: TJSONValue;
jObject: TJSONObject;
begin
Result := -1;
aRestClient := TRESTClient.Create(nil);
try
aRestResponse := TRESTResponse.Create(nil);
try
aRestRequest := TRESTRequest.Create(nil);
try
try
aRestClient.BaseURL := 'http://localhost:49272/api/test';
aRestRequest.Client := aRestClient;
aRestRequest.Response := aRestResponse;
aRestRequest.Method := rmPOST;
aRestRequest.Resource := 'hello';
aParam := aRestRequest.Params.AddItem;
aParam.Kind := pkREQUESTBODY;
aParam.name := 'helloData';
aParam.Value := TJson.ObjectToJsonString(AModel);
aRestRequest.Execute;
jValue := aRestResponse.JSONValue;
jObject := TJSONObject.ParseJSONValue(jValue.ToString) as TJSONObject;
Result := StrToIntDef((jObject.Get('status').JsonValue as TJSONString).Value, -1);
finally
FreeAndNil(jObject);
FreeAndNil(jValue);
end;
finally
FreeAndNil(aRestRequest);
end;
finally
FreeAndNil(aRestResponse);
end;
finally
FreeAndNil(aRestClient);
end;
end;
This code runs perfectly in win32 app, but fail on "aRestResponse := TRESTResponse.Create(nil);" when put into a dll.
I did not find rest client solution for delphi 2007. I end up using indy for this. I use LkJson to handle json.
class function TSampleApp.Hello(AModel: TModel): Integer;
var
idHttp: TIdHTTP;
url, sjsonresponse, sjsonrequest: string;
strRequest: TStrings;
jsonObj: TlkJSONobject;
begin
Result := -1;
url := 'http://localhost:49272/api/test/hello';
idHttp := TIdHTTP.Create;
try
jsonObj := TlkJSONobject.Create;
try
//populate
jsonObj.Add('param1', AModel.param1);
jsonObj.Add('param2', AModel.param2);
sjsonrequest := TlkJSON.GenerateText(jsonObj);
finally
FreeAndNil(jsonObj);
end;
idHttp.Request.Accept := 'application/json';
strRequest := TStringList.Create;
try
strRequest.Values['helloData'] := sjsonrequest;
sjsonresponse := idHttp.Post(url, strRequest);
finally
FreeAndNil(strRequest);
end;
jsonObj := TlkJSON.ParseText(sjsonresponse) as TlkJSONobject;
try
Result := StrToIntDef(VarToStr((jsonObj.Field['status'] as TlkJSONnumber).Value), -1);
finally
FreeAndNil(jsonObj);
end;
finally
idHttp.Free;
end;
end;
This code works also inside a dll.