Delphi 调用Java rest服务例子
时间: 2025-03-20 20:06:08 浏览: 27
### Delphi 中调用 Java RESTful 服务的实现
在 Delphi 中调用 Java 提供的 RESTful 服务可以通过 `TIdHTTP` 或者更现代的方式如 `REST.Client` 组件库完成。以下是具体方法以及代码示例。
#### 使用 TIdHTTP 调用 RESTful 接口
`TIdHTTP` 是 Indy 的核心组件之一,用于发送 HTTP 请求并接收响应数据。下面是一个简单的 GET 和 POST 请求示例:
```delphi
uses
IdHTTP, System.JSON;
function GetDepartment(const URL: string): string;
var
IdHTTP: TIdHTTP;
begin
IdHTTP := TIdHTTP.Create(nil);
try
Result := IdHTTP.Get(URL); // 发送 GET 请求
finally
IdHTTP.Free;
end;
end;
procedure AddDepartment(const URL: string; const DepartmentName: string);
var
IdHTTP: TIdHTTP;
Params: TStringStream;
begin
IdHTTP := TIdHTTP.Create(nil);
Params := TStringStream.Create('{"name": "' + DepartmentName + '"}', TEncoding.UTF8);
try
IdHTTP.Request.ContentType := 'application/json'; // 设置请求头为 JSON 类型
IdHTTP.Post(URL, Params); // 发送 POST 请求
finally
Params.Free;
IdHTTP.Free;
end;
end;
```
上述代码展示了如何通过 `TIdHTTP` 向 RESTful API 发起 GET 和 POST 请求[^1]。对于其他类型的请求(如 PUT、DELETE),可以分别使用 `Put` 和 `Delete` 方法。
#### 使用 REST.Client 调用 RESTful 接口
Delphi 自带的 `REST.Client` 单元提供了更高层次的支持,简化了与 RESTful 服务交互的过程。以下是如何利用该单元发起请求的一个例子:
```delphi
uses
REST.Client, REST.Types, System.JSON;
function FetchDepartment(const BaseURL, DeptNo: string): TJSONObject;
var
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
RESTResponse: TRESTResponse;
begin
RESTClient := TRESTClient.Create(BaseURL);
RESTRequest := TRESTRequest.Create(nil);
RESTResponse := TRESTResponse.Create(nil);
try
RESTClient.BaseURL := BaseURL;
RESTRequest.Method := rmGET;
RESTRequest.Resource := Format('/v2/depts/%s', [DeptNo]); // 动态设置资源路径
RESTRequest.Execute;
Result := TJSONObject.ParseJSONValue(RESTResponse.Content) as TJSONObject; // 解析返回的 JSON 数据
finally
RESTResponse.Free;
RESTRequest.Free;
RESTClient.Free;
end;
end;
procedure UpdateDepartment(const BaseURL, DeptNo, NewName: string);
var
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
Body: TBody;
begin
RESTClient := TRESTClient.Create(BaseURL);
RESTRequest := TRESTRequest.Create(nil);
try
RESTClient.BaseURL := BaseURL;
RESTRequest.Method := rmPUT;
RESTRequest.AddBody(TJSONString.Create('{"name": "' + NewName + '"}'), ctAPPLICATION_JSON); // 添加 JSON 格式的主体
RESTRequest.Resource := Format('/v1/depts/%s', [DeptNo]);
RESTRequest.Execute;
finally
RESTRequest.Free;
RESTClient.Free;
end;
end;
```
这段代码演示了如何使用 `REST.Client` 来执行 GET 和 PUT 请求[^3]。注意,在实际项目中可能还需要处理异常情况和验证服务器返回的状态码。
---
### 总结
无论是采用传统的 `TIdHTTP` 还是现代化的 `REST.Client` 方案,都可以轻松地让 Delphi 客户端应用程序连接到由 Java 实现的 RESTful Web Service 上。选择哪种方式取决于项目的复杂度和个人偏好。
阅读全文
相关推荐












