Setting HeaderFields for Bearer Token to make API requests

10 ビュー (過去 30 日間)
Noah Walcutt
Noah Walcutt 2019 年 6 月 3 日
回答済み: Sam Oliver 2023 年 2 月 21 日
I need to set the Bearer Token field to 'Authorization : "Bearer <token>"' to pull data from an API however I have not been able to set this value. I have tried using the weboptions() function, but the HeadersFields field will not accept strings -- it appears to only accept numeric-type.
r= weboptions;
r.HeaderFields = 'Authorization : "Bearer <token>"';
This gives an error (r2019a). What's wrong with this statment?

回答 (2 件)

Mahsa Eshtehardi
Mahsa Eshtehardi 2019 年 11 月 5 日
You should add brackets:
'HeaderFields',{'Authorization', ['Bearer ' token]});

Sam Oliver
Sam Oliver 2023 年 2 月 21 日
You can make a request using Bearer token base authentication using the following code.
function [resp, a, req] = webread2(URL,Message,BearerToken)
MyBody = matlab.net.http.MessageBody(Message);
MyHTTPOptions = matlab.net.http.HTTPOptions();
Request = matlab.net.http.RequestMessage;
Request.Method = 'POST';
Request.Header = matlab.net.http.HeaderField('Content-Type','application/json','Authorization', ['Bearer ' BearerToken]);
Request.Body = MyBody;
uri = matlab.net.URI(URL);
[resp, a, req] = Request.send(uri,MyHTTPOptions);
end

カテゴリ

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