我在DelphiXe7上使用以下代码向RESTAPI发出请求。它工作得很好,除非发生内部服务器错误之类的错误。在这种情况下,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;
小提琴手一切看起来都很好。当发生错误(如内部服务器错误)时,如何获取实际状态代码和响应主体?
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;
RESTClient有一个属性RaiseExceptionOn500,它可能有助于捕获此错误