Я пытаюсь перевести исходный код Java для получения актуальной информации о погоде из RSS-канала погоды Yahoo в MATLAB.
Исходный источник Java, предоставленный Yahoo, можно найти, перейдя по этой ссылке:
https://developer.yahoo.com/weather/documentation.html#oauth-java
Я попытался аккуратно перевести весь исходный код Java в MATLAB с помощью страниц документации MATLAB и Oracles, где я использовал функции в MATLAB, которые наиболее похожи на функции в Java.
Вот код MATLAB, предназначенный для перевода исходного кода Java:
import matlab.net.*
import matlab.net.http.*
%{
parametersList ==
format=xml&location=sunnyvale%2Cca&oauth_consumer_key=your-consumer-key&oauth_nonce=20DH3PP&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1556941167&oauth_version=1.0
Bugs:
1. sort method in matlab does not work the same as Java's Sort Method
2. Get rid of the 'oauth_nonce' string in parametersList
%}
% This function downloads Weather API information
app_id = "aWfYyT5c"
consumer_key = "dj0yJmk9bW9XRk02ejM5azZNJnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PTM4"
client_secret = "060782ac21ac35e2ef234316e01f9251b2dfe070"
url = "https://weather-ydn-yql.media.yahoo.com/forecastrss"
t = datetime('now') % gives correct date and time
p = round(posixtime(t)/1000,0)
timestamp = p
%nonce = uint8(32)
nonce = ""
for i=1:1:7
nonce(i) = char(randi(127))
if isletter( nonce(i) ) == 0
nonce(i) = char(65)
end
end
get_rid_of = ""+ char(92) + char(92) + char(87) %char(34) + char(34) + char(92)
new_str = ""
newStr = replace(nonce,get_rid_of,new_str)
oauthNonce = ""
for i=1:1:7
oauthNonce = strcat(oauthNonce,char(newStr(i)))
end
parameters_0 = "oauth_consumer_key=" + consumer_key
parameters_1 = "oauth_nonce=" + oauthNonce
parameters_2 = "oauth_signature_method=HMAC-SHA1"
parameters_3 = "oauth_timestamp="+timestamp
parameters_4 = "oauth_version=1.0"
parameters_5 = "location="+native2unicode("lubbock,tx",'UTF-8')
parameters_6 = "format=xml" % Masen recommends xml
parameters = [parameters_0,parameters_1,parameters_2,parameters_3,parameters_4,parameters_5,parameters_6]
sort(parameters)
%{
parametersList ==
format=xml&location=sunnyvale%2Cca&oauth_consumer_key=your-consumer-key&oauth_nonce=20DH3PP&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1556941167&oauth_version=1.0
Bugs:
1. sort method in matlab does not work the same as Java's Sort Method
2. Conjoin oauthNonce into one large string: Use strcat repeatedly! to
append each char to one large string
%}
parametersList = ""
parametersList = parameters_6 + "&" + parameters_5 + "&" + parameters_0 + "&" + parameters_1 + "&" + parameters_2 + "&" + parameters_3 + "&" + parameters_4
signatureString = "GET&" + native2unicode(url,'UTF-8') + "&" + native2unicode(parametersList,'UTF-8')
%Try catch goes here
try
secret = client_secret + "&"
signature = HMAC_M(secret, 'SHA-1', 'base64')
signature = base64encode(signature)
catch
fprintf("Unable to append signature\n")
return
end
%{
Message Authentication code here
%}
% char(34) represents ASCII character:"
%{
The following is a generated format of how the authorizationLine should
look like, based on the Java code:
OAuth oauth_consumer_key="your-consumer-key", oauth_nonce="BdsF26e", oauth_timestamp="1556986567", oauth_signature_method="HMAC-SHA1", oauth_signature="LLqHYOA/3LWCdNtYUa9z89Z3aV0=", oauth_version="1.0"
%}
authorizationLine = "";
authorizationLine = authorizationLine + "OAuth " + "oauth_consumer_key=" + char(34) + consumer_key + char(34) + ", " + "oauth_nonce=" + char(34) + oauthNonce + char(34) + ", " + "oauth_timestamp=" + char(34) + timestamp + char(34) + ", " + "oauth_signature_method=" + char(34) + "HMAC-SHA1" + char(34) + ", " + "oauth_signature=" + char(34) + signature + char(34) + ", " + "oauth_version=" + char(34) + "1.0" + char(34) + ""
%{
%authorizationLine = strcat(authorizationLine,temp)
Author = "";
Author = Author + "oauth_nonce=" + char(34) + oauthNonce + char(34) + ", "+ "oauth_timestamp=" + char(34) + timestamp + char(34) +", "+ "oauth_signature_method=" + char(34) + "HMAC-SHA1" + char(34) + ", "+ "oauth_signature=" + char(34) + signatureString + char(34) + ", "+ "oauth_version=" + char(34) + "1.0" + char(34) + ""
authorizationLine = authorizationLine + "oauth_nonce=" + char(34) + oauthNonce + char(34) + ", "
authorizationLine = authorizationLine + "oauth_timestamp=" + char(34) + timestamp + char(34) +", "
authorizationLine = authorizationLine + "oauth_signature_method=" + char(34) + "HMAC-SHA1" + char(34) + ", "
authorizationLine = authorizationLine + "oauth_signature=" + char(34) + signatureString + char(34) + ", "
authorizationLine = authorizationLine + "oauth_version=" + char(34) + "1.0" + char(34) + ""
%}
uri = matlab.net.URI(url + "?location=lubbock,tx&format=xml");
obj1 = matlab.net.http.HeaderField("Authorization",authorizationLine)
%obj1 = matlab.net.http.field.GenericField("Authorization", authorizationLine(1) )
obj2 = matlab.net.http.HeaderField("X-Yahoo-App-Id",app_id)
%obj2 = matlab.net.http.field.GenericField("X-Yahoo-App-Id" , app_id);
obj3 = matlab.net.http.field.ContentTypeField("application/xml")
%obj3 = matlab.net.http.field.GenericField("Content-Type", "application/xml");
%change all xml to xml or we will not be able to decode the info
%[response,completerequest,history] = send(r,url)
r = RequestMessage
resp = send(r,uri)
status = resp.StatusCode
ПРИМЕЧАНИЕ. Для HMAC_M используется специальная внешняя функция. Я получил исходный код для HMAC_M по следующей ссылке:
https://www.mathworks.com/matlabcentral/fileexchange/46182-hmac-hash-message-authentication-code-function
Код для HMAC_M был слишком велик, чтобы вставить его сюда.
На данный момент выдается следующее сообщение StatusCode:
resp =
ResponseMessage with properties:
StatusLine: 'HTTP/1.1 401 Unauthorized'
StatusCode: Unauthorized
Header: [1×15 matlab.net.http.HeaderField]
Body: [1×1 matlab.net.http.MessageBody]
Completed: 0
status =
StatusCode enumeration
Unauthorized
Каковы ваши рекомендации для обеспечения авторизации?