1

I have an application that calls a REST API. The API takes a JSON as input and returns the results also in JSON format.

When I try to send a duplicate value to the API, the idHTTP.ResponseCode contains 406 and the IdHTTP1.ResponseText contains 'HTTP/1.1 406 Not Acceptable'. The API also returns a JSON that explains the error and will look something like this: {"Message": "failed to insert record - possible duplicate"}

My Question is: Where do I find the response JSON, especially if the request fails? I thought it would be in the IdHTTP1.ResponseText but it obviously is not.

Here is the result of the same call made from Insomnia, one can see the Code is 406 and the Text is Not Acceptable. It also lists the return JSON which means it must be available somewhere.

enter image description here

Here is my code, both POST options are listed. Both the POSTs do not return anything and the ShowMessage with the results will be blank in both cases. I also tried saving the result to file but it only created an empty file.

procedure TfrmJSonPlay.btnMakeAppointmentClick(Sender: TObject);
var
  IdHTTP1: TIdHTTP;
  loJson: TJSONObject;
  loReqJson: TStringStream;
  loRespJson: TMemoryStream;
  liSuper: iSuperObject;
  lsHttpAnswer: string;
begin
  IdHTTP1 := TIdHTTP.Create();
  loJson  := TJSONObject.Create;
  loRespJson := TMemoryStream.Create();
  try
    BuildJSon(loJson); // Build request JSON
    loReqJson := TStringStream.Create(loJson.ToString, TEncoding.UTF8);
    try
      IdHttp1.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create();
      try
        IdHTTP1.Request.ContentType := 'application/json';
        IdHTTP1.Post('https://my.url.com/central-processor/makeBooking', loReqJson, loRespJson);
        //lsHttpAnswer := IdHTTP1.Post('https://my.url.com/central-processor/makeBooking', loReqJson);
      except
        // Suppress errors, we will work with the Http.ResponseCode and ResponseText
      end;

      loRespJson.Position := 0;
      //loRespJSon.SaveToFile('C:\loRespJSon.Txt');
      liSuper := loRespJson.ToJson();
      ShowMessage('HTTP ResponseText: ' + IdHTTP1.ResponseText + CHAR(13)+
                  'HTTP ResponseCode: ' + IntToStr(idHttp1.ResponseCode) + CHAR(13)+
                  'HTTP Answer: ' + lsHttpAnswer + CHAR(13)+
                  'HTTP JSon Response: ' + liSuper.S['message']);
    finally
      FreeAndNil(loReqJson);
    end;
  finally
    FreeAndNil(IdHTTP1);
    FreeAndNil(loJson);
    FreeAndNil(loRespJson);
  end;
end;

I did find this post and tried both Receive solutions but neither worked: IdHttp : how to deal with json request and response

Johan
  • 317
  • 3
  • 11

0 Answers0