Trying to make authorization post call with HTTP post

조회 수: 6 (최근 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 CenterFile Exchange에서 Call 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