Trying to make authorization post call with HTTP post

10 Ansichten (letzte 30 Tage)
Hank Helmers
Hank Helmers am 13 Apr. 2022
Beantwortet: Suraj am 15 Sep. 2023
Hello, I am trying to access a spotify access token using matlab's api requests, and at the moment I just get a 'Bad Request' output and I was wondering if anyone had any ideas?
I have to have the content type of the urlencoded, and a header with Authorization and my id and secret id encoded.
client_id = "ID";
secret_id = "SECRET";
encodedId = base64encode(strcat(client_id, ":", secret_id));
disp(encodedId);
headerField = HeaderField('Content-Type', 'application/x-www-form-urlencoded', "Authorization", strcat("Basic ", encodedId));
inputParameters = struct('grant_type', "authorization_code", "code", auth_code, "redirect_uri", redirect_uri);
aTest = jsonencode(inputParameters);
options = HTTPOptions();
method = RequestMethod.POST;
request = RequestMessage(method,headerField, aTest)
show(request)
resp = send(request,token_url, options);
disp(resp)

Antworten (1)

Suraj
Suraj am 15 Sep. 2023
Hi Hank,
I understand that you're trying to send a POST request to a Spotify API. For this you'll have to send "grant_type", "code" and "redirect_uri" as query parameters because the request content type is "application/x-www-form-urlencoded".
In the code snippet you've attached however, this payload is being sent as JSON-encoded string. Please refer to the code snippet below to learn how you can compose this HTTP request correctly.
client_id = "ID";
secret_id = "SECRET";
encodedId = base64encode(strcat(client_id, ":", secret_id));
disp(encodedId);
headerField = HeaderField('Content-Type', 'application/x-www-form-urlencoded', "Authorization", strcat("Basic ", encodedId));
% Use the "FormProvider" class to create a URI query string
inputParameters = matlab.net.http.io.FormProvider('grant_type', "authorization_code", "code", auth_code, "redirect_uri", redirect_uri);
options = HTTPOptions();
method = RequestMethod.POST;
request = RequestMessage(method,headerField, inputParameters)
show(request)
resp = send(request,token_url, options);
disp(resp)
In the above code snippet, "FormProvider" creates data suitable for a request message whose Content-Type is "application/x-www-form-urlencoded". You can also achieve this using "QueryParameter" class.
Please refer to the documentation for more details:
  1. "FormProvider" class: https://www.mathworks.com/help/matlab/ref/matlab.net.http.io.formprovider-class.html
  2. "QueryParameter" class: https://www.mathworks.com/help/matlab/ref/matlab.net.queryparameter-class.html
I hope this resolves your query.
Thanks & regards,
Suraj.

Kategorien

Mehr zu Call Web Services from MATLAB Using HTTP finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by