gpt4 book ai didi

rest - TRESTRequest 遇到错误时获取响应体和状态码

转载 作者:行者123 更新时间:2023-12-03 18:40:50 38 4
gpt4 key购买 nike

我在 Delphi XE7 上使用以下代码向 REST API 发出请求。它运行良好,除非发生诸如内部服务器错误之类的错误。在这种情况下,StatusCode 是 0(而它应该是 500)并且 Content 只返回响应头(而我需要响应主体)。

var
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
begin
try
RESTClient:= TRESTClient.Create('http://blah.example.com');
RESTRequest:= TRESTRequest.Create(nil);
RESTRequest.Method:= TRESTRequestMethod.rmGET;
RESTRequest.Resource:= 'customers';
RESTRequest.Accept:= 'application/json';
RESTRequest.Client:= RESTClient;
RESTRequest.Execute;
finally
RESTClient.Free;
RESTRequest.Free;
end;

Fiddler 中的一切看起来都很好。发生错误(如Internal Server Error)时如何获取实际状态码和响应体?

最佳答案

function Funcion(BaseURL: string; UrlAuth: string; Usuario: string; Password: string): string;
var
RESTClient : TRESTClient;
RESTRequest : TRESTRequest;
RESTResponse : TRESTResponse;
JSONMensaje : TJSONObject;
JSONResponse : TJSONObject;
jValue : TJSONValue;
Token : string;
begin
Result := '';
RESTClient := TRESTClient.Create(nil);
RESTRequest := TRESTRequest.Create(nil);
JSONMensaje := TJSONObject.Create;
try
Result := '';
RESTClient.BaseURL := BaseURL;
RESTClient.Accept := 'application/json';
RESTClient.AcceptCharSet := 'UTF-8';
RESTClient.ContentType := 'application/json';
RESTClient.RaiseExceptionOn500 := true;
// Se inicia el mensaje JSON a enviar
JSONMensaje.AddPair('username', Usuario);
JSONMensaje.AddPair('password', Password);

RESTRequest.Method := TRESTRequestMethod.rmPOST;
RESTRequest.Client := RESTClient;

RESTClient.Params.Clear;
RESTRequest.Params.Clear;
RESTRequest.ClearBody;
RESTRequest.Resource := UrlAuth;
RESTRequest.Params.AddItem('', JSONMensaje.ToString, pkREQUESTBODY, [poDoNotEncode],
TRESTContentType.ctAPPLICATION_JSON);

RESTResponse := TRESTResponse.Create(nil);
RESTRequest.Response := RESTResponse;

RESTRequest.Accept := 'application/json';
try
RESTRequest.Execute;
if Assigned(RESTResponse.JSONValue) then
begin
jValue := RESTResponse.JSONValue;

// Parsear el JSON
JSONResponse := TJSONObject.Create;
JSONResponse := RESTResponse.JSONValue as TJSONObject;
if RESTResponse.StatusCode = 200 then
begin
if Assigned(JSONResponse.GetValue('valor')) then
begin
Token := JSONResponse.GetValue('valor').ToString;
end
end
else
begin
if Assigned(JSONResponse.GetValue('error')) then
begin
Result := 'Error: ' + JSONResponse.GetValue('error').ToString;
end;
end;
RESTResponse.Free;
JSONResponse.Free;
end;
except on E:Exception do
begin
Result := 'Error: ' + RESTResponse.ErrorMessage + ' Error: ' + E.Message;
end;
end;
finally
RESTClient.Free;
RESTRequest.Free;
JSONMensaje.Free;
end;
end;

关于rest - TRESTRequest 遇到错误时获取响应体和状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410510/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com