Jump to content
narag

TIdHTTP blank response when status code 400

Recommended Posts

Hello,

 

I'm using TIdHttp to POST to a partner's HTTPS server. It takes raw JSON and answers also with JSON. 

 

The server guys return a 400 Bad Request for application validation errors. I don't think that's a good idea, but not sure they will accept my suggestion to change it.

 

I've included hoNoProtocolException in HttpOptions. But still TIdHTTP.Post returns an empty string. The property ResponseText returns "HTTP 400 Bad Request" but testing with Postman I see:

 

{
    "status": 400,
    "message": "Duplicate transaction reference. Please use a unique reference."
}

 

I need that JSON to know what exactly went wrong with the request.

 

Tried using an output stream, but also got a blank result. Last incarnation of the code, looking in Response.ContentStream (also empty):

 

function TXXXXConnection.Post(URL, Content: string): Boolean;
var
    InStream, OutStream: TStringStream;
    Response: string;
begin
    Http.Request.CustomHeaders.Values['x-client-id'] := XXXXXX;
    Http.Request.CustomHeaders.Values['x-client-secret'] := YYYYYY;
    Http.Request.ContentType := 'application/json';
    Http.Request.Accept := '*/*';
    Http.HttpOptions := Http.HttpOptions + [hoNoProtocolErrorException];
    InStream := TStringStream.Create(Content);
    OutStream := TStringStream.Create('');
    try
        OutputObject := SO(Http.Post(BaseURL + URL, InStream));
        Result := Http.ResponseCode = 200;
        if not Result then begin
           OutStream.CopyFrom(Http.Response.ContentStream);
           OutputObject := SO('{"error": "' + OutStream.DataString + '"}');
        end;
    finally
        InStream.Free;
        OutStream.Free;
    end
end;

 

It seems that the response JSON is discarded when status code is an HTTP error. Or can I access it using another property?

 

Thanks in advance,

 

   Nico

Share this post


Link to post
24 minutes ago, Brian Evans said:

That was it, thank you very much!

 

It seems I was using a very outdated version of the docs... added in 2016.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×