フィルターのクリア

Trying to make authorization post call with HTTP post

7 ビュー (過去 30 日間)
Hank Helmers
Hank Helmers 2022 年 4 月 13 日
回答済み: Suraj 2023 年 9 月 15 日
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)

回答 (1 件)

Suraj
Suraj 2023 年 9 月 15 日
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.

カテゴリ

Help Center および File ExchangeCall Web Services from MATLAB Using HTTP についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by