MATLAB: Inconsistent connection to Restful api using the HTTP interface

http interfacematlab.net.http.field.genericfieldmatlab.net.http.httpoptions

The site i am connecting provide a public and private key for Restful connection. They provided a JAVA example to connect so i tried to re-implement it. I have created my own RequestMessage header(date,method,authorization,accept) with matlab.net.http.field.GenericField which contain hmacsha1 of pivate key,message followed by base64 encoding.
I have managed to get the Restful api data but most of the time it give me 401 unauthorized error so i need to run the script three to five times to get authenticated. Is this a normal behaviour when using the http interface? When i use the site provided python and java application it can connect without this behaviour.
clc;clear all;
cy_public = 'bedaf676-bab0-4e25-xx-xx';
cy_private = '30a236a4-ab5c-4514-xx-xx';
suburl = '/api/annotation/5357434.json';
url = ['http://example.edu.my',suburl];
formatOut = 'ddd, dd mmm yyyy HH:MM:SS';
tt = datetime('now','TimeZone','UTC');
cy_date = [datestr(tt,formatOut),' +0000'];
cy_url = [newline,suburl];
cy_action = ['GET',newline,newline,newline];
hmac = System.Security.Cryptography.HMACSHA1(uint8(cy_private)).ComputeHash(uint8([cy_action,cy_date,cy_url]));
cy_sha1 = native2unicode(hmac);
%%%cy_sha1 = doHMAC_SHA1([cy_action,cy_date,cy_url],cy_private);
payload = base64encode(cy_sha1);
cy_sign=['CYTOMINE ',cy_public,':',payload];
cy_header_1 = matlab.net.http.field.GenericField('date',cy_date);
cy_header_2 = matlab.net.http.field.GenericField('X-Requested-With','XMLHttpRequest');
cy_header_3 = matlab.net.http.field.GenericField('authorization',cy_sign);
cy_header_4 = matlab.net.http.field.GenericField('accept','application/json,*/*');
cy_header_5 = matlab.net.http.field.GenericField('Accept-Encoding','identity');
header = [cy_header_5 cy_header_1 cy_header_2 cy_header_3 cy_header_4];
reqline = matlab.net.http.RequestLine('GET',cy_url,'HTTP/1.1');
cy_req = matlab.net.http.RequestMessage(reqline,header,[]);
uri = matlab.net.URI(url);
options = matlab.net.http.HTTPOptions('Authenticate',false);
[response,completedrequest,history] = send(request,uri,options);
response.Body.Data % shows the json data

Best Answer

solve this by changing the base64encode function that i get from fileexchange into matlab built in base64encode called matlab.net.base64encode