How can I access all characters of a token when accessing an API?

8 次查看(过去 30 天)
When I make a request for a token, I get a token with a length of 878 characters, but it must be 931 characters, I don't get all the characters. My code is like this:
%ADFS parameters
client_id = 'client_id';
client_secret = 'client_secret';
url = 'url:host';
resource = 'urn:email';
grant_type = 'grant_type';
%Rearrangement of information to create the data variable
data = [...
'redirect_uri=', resource,...
'&client_id=', client_id,...
'&client_secret=', client_secret,...
'&grant_type=', grant_type];
response = webwrite(url,data); %We send and receive the response
strlength(response.access_token)
access_token = response.access_token; %We get the token from the response variable
When I use postman I manage to get the required 931 characters, but if I use MatLab I can't. Can you help me to solve this problem and be able to receive all the characters?

回答(1 个)

T.Nikhil kumar
T.Nikhil kumar 2023-10-25
Hello Luis,
I can understand that you're facing an issue related to the length of the access token you receive when making a request using MATLAB compared to when using Postman.
This discrepancy in the length of the token could be due to the way MATLAB handles the response.
I would suggest you to try handling the response as a 'JSON' object instead of a 'struct' using the ‘JSONLab’ library. This library contains certain functions to deal with JSON type data. You can add the below mentioned steps to your code.
  1. You can specify the ‘data’ argument as struct since the “MediaType” would be ‘json’ now.
  2. You can convert the ‘data’ struct to JSON string using ‘savejson’ function from the JSONLab library.
  3. Set the ‘ContentTypeHeaderField to ‘application/json’ to indicate that the content of the request is in JSON format.
  4. Parse this JSON type ‘response’ into a struct using the ‘loadjson’ function and now get the access token using dot indexing.
Refer to the below mentioned code snippet:
% Rearrangement of information to create the data struct
data = struct(...
'redirect_uri', resource,...
'client_id', client_id,...
'client_secret', client_secret,...
'grant_type', grant_type);
% Convert the data to a JSON string
dataJson = savejson('', data);
% Set the HTTP headers to deal with JSON type data
headers = {'Content-Type', 'application/json'};
% Send the request and receive the response
response = webwrite(url, dataJson, weboptions('HeaderFields', headers));
% Parse the JSON response
responseJson = loadjson(response);
% Retrieve the access token
access_token = responseJson.access_token;
% Check the length of the access token
strlength(access_token)
You can download the JSONLab library and add it to MATLAB path from here:
Refer to the following documentation to understand more about ‘weboptions’:
Hope this helps!

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by