首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi idhttp.Post 呼叫 DataSnap REST 遠端方法:必須加上 update 前綴的關鍵細節

     編輯:Delphi

前言

Delphi DataSnap REST 架構下,客戶端使用 TIdHTTP 以 POST 方式呼叫伺服器方法時,有一個極易踩坑的規則:遠端方法名稱必須以 "update" 為前綴,否則伺服器會返回 404 或「方法不存在」錯誤。本文記錄此關鍵細節與完整調用代碼。

伺服器端方法定義(關鍵:update 前綴)

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;

關鍵點總結

  1. 方法命名規則: DataSnap REST 針對 POST 請求,強制要求方法名以 update 開頭(對應 HTTP POST 語意),GET 請求則無此限制(對應查詢語意)。
  2. URL 結構: /datasnap/rest//。
  3. 參數編碼: 使用 TIdURI.ParamsEncode 處理中文/特殊字元。
  4. Content-Type: 必須設為 application/x-www-form-urlencoded,伺服器才能正確反序列化參數。
  5. 回傳格式: DataSnap REST 預設回傳 JSON 陣列結構 {"result":[...]},需用 TJSONObject 解析。

對比:GET 請求調用(無需 update 前綴)

// 伺服器方法
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,請優先檢查方法命名是否符合此規則。此文為個人摸索半天得出,分享給踩坑的同行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved