Search code examples
restdelphioauth-2.0indy

I receive a unsupported media type error when doing a rest request using oauth


I'm using delphi 11.3 to make a rest request using oauth2. I get the token, then I need to call again another api to send my json and the token. I'm receiving "unsupported media type" can I have some help? this is the code used for testing:

var slJSON: TStringList;
begin
  slJSON := TStringList.Create;
  slJSON.LoadFromFile('c:\temp\json.txt');

  // Get TOKEN
  OAuth2Authenticator1.ClientID     := 'xxx';
  OAuth2Authenticator1.ClientSecret := 'yyy';
  OAuth2Authenticator1.Scope := 'zzz';
  OAuth2Authenticator1.AccessTokenEndpoint := 'mylink';
  OAuth2Authenticator1.AuthorizeWithClientCredentials;

  RESTRequest1.Method  := rmPOST;
  RESTClient1.BaseURL := 'mylink2';
  RESTRequest1.Resource := 'myfunction';

  // BOOKING
  with RESTRequest1.Params.AddItem do
   begin
     Name  := 'test';
     Value := slJSON.Text;
     ContentType := TRESTContentType.ctAPPLICATION_JSON;
     Kind := TRESTRequestParameterKind.pkREQUESTBODY;
   end;

  with RESTRequest1.Params.AddItem do
    begin
      Options := [];
      Options := Options + [TRESTRequestParameterOption.poDoNotEncode];
      Name := 'Authorization';
      Value := 'Bearer ' + OAuth2Authenticator1.AccessToken;
      Kind := TRESTRequestParameterKind.pkHTTPHEADER;
      ContentType := TRESTContentType.ctTEXT_PLAIN;
    end;

  RESTRequest1.Execute;

  slJSON.Free;
end;

Can I have some help? Thank you


Solution

  • I have solved the problem myself:

    1. I had to move the authorization param before the other param
    2. I had to change the kind of the json.

    Like this it works:

    var slJSON: TStringList;
    begin
      slJSON := TStringList.Create;
      slJSON.LoadFromFile('c:\temp\json.txt');
    
      // Get TOKEN
      OAuth2Authenticator1.ClientID     := 'xxx';
      OAuth2Authenticator1.ClientSecret := 'yyy';
      OAuth2Authenticator1.Scope := 'zzz';
      OAuth2Authenticator1.AccessTokenEndpoint := 'mylink';
      OAuth2Authenticator1.AuthorizeWithClientCredentials;
    
      RESTRequest1.Method  := rmPOST;
      RESTClient1.BaseURL := 'mylink2';
      RESTRequest1.Resource := 'myfunction';
    
      // BOOKING
      with RESTRequest1.Params.AddItem do
        begin
          Options := [];
          Options := Options + [TRESTRequestParameterOption.poDoNotEncode];
          Name := 'Authorization';
          Value := 'Bearer ' + OAuth2Authenticator1.AccessToken;
          Kind := TRESTRequestParameterKind.pkHTTPHEADER;
          ContentType := TRESTContentType.ctTEXT_PLAIN;
        end;
    
      with RESTRequest1.Params.AddItem do
       begin
         Name  := 'test';
         Value := slJSON.Text;
         ContentType := TRESTContentType.ctAPPLICATION_JSON;
         Kind := TRESTRequestParameterKind.pkGETorPOST;
       end;