Delphi DataSnap REST 架構下,客戶端使用 TIdHTTP 以 POST 方式呼叫伺服器方法時,有一個極易踩坑的規則:遠端方法名稱必須以 "update" 為前綴,否則伺服器會返回 404 或「方法不存在」錯誤。本文記錄此關鍵細節與完整調用代碼。
type
TServerMethods1 = class(TDataModule)
public
{ 必須命名為 updateEcho,否則 POST 請求無法路由 }
function updateEcho(const Value: string): string;
end;
function TServerMethods1.updateEcho(const Value: string): string;
begin
Result := Value; // 簡單回傳原字串
end;
uses
IdHTTP, IdURI, System.JSON, SysUtils;
procedure TForm1.btnPostClick(Sender: TObject);
var
HTTP: TIdHTTP;
Params: TStringList;
Response: string;
JSONObj: TJSONObject;
begin
HTTP := TIdHTTP.Create(nil);
Params := TStringList.Create;
try
HTTP.Request.ContentType := 'application/x-www-form-urlencoded';
HTTP.Request.Accept := 'application/json';
{ 參數名必須與伺服器方法參數名一致:Value }
Params.Add('Value=' + TIdURI.ParamsEncode(edtInput.Text));
{ URL 格式:https://host:port/datasnap/rest/TServerMethods1/updateEcho }
Response := HTTP.Post('https://localhost:8080/datasnap/rest/TServerMethods1/updateEcho', Params);
{ 解析 JSON 回傳:{"result":["回傳字串"]} }
JSONObj := TJSONObject.ParseJSONValue(Response) as TJSONObject;
try
if Assigned(JSONObj) then
ShowMessage('伺服器回傳: ' + JSONObj.GetValue('result').AsString);
finally
JSONObj.Free;
end;
finally
Params.Free;
HTTP.Free;
end;
end;
update 開頭(對應 HTTP POST 語意),GET 請求則無此限制(對應查詢語意)。/datasnap/rest// 。TIdURI.ParamsEncode 處理中文/特殊字元。application/x-www-form-urlencoded,伺服器才能正確反序列化參數。{"result":[...]},需用 TJSONObject 解析。// 伺服器方法
function TServerMethods1.GetData(const ID: Integer): string;
// 客戶端 GET
Response := HTTP.Get('https://localhost:8080/datasnap/rest/TServerMethods1/GetData?ID=123');
「POST 必須 update 前綴」是 DataSnap REST 設計時為了符合 RESTful 語意(POST 對應建立/更新操作)而強制的約定。開發時若遇到 POST 總是 404,請優先檢查方法命名是否符合此規則。此文為個人摸索半天得出,分享給踩坑的同行。