DataSnap开发非常好用,其它不说了,直接上干货:
创建一个DataSnap REST应用
ServerMethodsUnit1代码如下:
unit ServerMethodsUnit1;
interface
uses
System.SysUtils, System.Classes, System.Json,
DataSnap.DSProviderDataModuleAdapter,
Datasnap.DSServer, Datasnap.DSAuth;
type
TServerMethods1 = class(TDSServerModule)
private
{ Private declarations }
public
{ Public declarations }
//Restful接口测试
//GET
function Test(Value: string): string;
//POST
function updateTest(Value: string; Obj: TJSONObject): string;
//DELETE
function cancelTest(Value: string): string;
//PUT
function acceptTest(Value: string; Obj: TJSONObject): string;
end;
implementation
{%CLASSGROUP 'System.Classes.TPersistent'}
{$R *.dfm}
uses
System.StrUtils, Data.DBXPlatform;
//GET
function TServerMethods1.Test(Value: string): string;
var
p1: string;
p2: string;
begin
p1 := GetInvocationMetadata.QueryParams.Values['p1'];
p2 := GetInvocationMetadata.QueryParams.Values['p2'];
Result := Format('Test called,Value:%s,p1:%s,p2:%s',[Value,p1,p2]);
end;
//POST
function TServerMethods1.updateTest(Value: string; Obj: TJSONObject): string;
var
p1: string;
p2: string;
data1: string;
data2: string;
begin
p1 := GetInvocationMetadata.QueryParams.Values['p1'];
p2 := GetInvocationMetadata.QueryParams.Values['p2'];
if Obj <> nil then
begin
data1 := obj.GetValue('data1').ToJSON;
data2 := obj.GetValue('data2').ToJSON;
end;
Result := Format('updateTest called,Value:%s,p1:%s,p2:%s,data1:%s,data2:%s',[Value,p1,p2,data1,data2]);
end;
//DELETE
function TServerMethods1.cancelTest(Value: string): string;
var
p1: string;
p2: string;
begin
p1 := GetInvocationMetadata.QueryParams.Values['p1'];
p2 := GetInvocationMetadata.QueryParams.Values['p2'];
Result := Format('cancelTest called,Value:%s,p1:%s,p2:%s',[Value,p1,p2]);
end;
//PUT
function TServerMethods1.acceptTest(Value: string; Obj: TJSONObject): string;
var
p1: string;
p2: string;
data1: string;
data2: string;
begin
p1 := GetInvocationMetadata.QueryParams.Values['p1'];
p2 := GetInvocationMetadata.QueryParams.Values['p2'];
if Obj <> nil then
begin
data1 := obj.GetValue('data1').ToJSON;
data2 := obj.GetValue('data2').ToJSON;
end;
Result := Format('acceptTest called,Value:%s,p1:%s,p2:%s,data1:%s,data2:%s',[Value,p1,p2,data1,data2]);
end;
end.
客户端请求用Delphi自带的工具进行测试(源代码在Embarcadero\Studio\20.0\source\data\rest\restdebugger,可以学习怎么提交请求)。
GET调用结果:
POST调用结果:
PUT调用结果:
DELETE调用结果: