delphi如何通过http请求获取json返回值
时间: 2023-06-14 07:03:57 浏览: 110
Delphi 可以使用 TIdHTTP 组件来发送 HTTP 请求,然后使用 TJSONObject 类来解析返回的 JSON 数据。
以下是一个简单的示例代码:
```delphi
uses
IdHTTP, System.JSON;
function GetJSONFromURL(const URL: string): TJSONObject;
var
HTTP: TIdHTTP;
Response: string;
begin
HTTP := TIdHTTP.Create(nil);
try
Response := HTTP.Get(URL);
Result := TJSONObject.ParseJSONValue(Response) as TJSONObject;
finally
HTTP.Free;
end;
end;
```
在示例中,我们创建了一个 TIdHTTP 实例,然后使用 Get 方法发送 HTTP 请求并获取响应内容。接着,我们使用 TJSONObject.ParseJSONValue 方法将响应内容解析为 TJSONObject 类型的对象并返回。
你可以将该函数添加到你的应用程序中,然后通过调用该函数并传入你需要获取 JSON 数据的 URL 来获取 JSON 数据。例如:
```delphi
var
JSON: TJSONObject;
begin
JSON := GetJSONFromURL('http://example.com/data.json');
try
// 处理 JSON 数据
finally
JSON.Free;
end;
end;
```
注意,在处理完 JSON 数据后,需要释放 TJSONObject 对象的内存空间,以避免内存泄漏。