問題描述
在 MATLAB 中通過 HTTP 接收數據 (Receive data via HTTP in MATLAB)
我已經在 MATLAB 論壇上發布了這個問題,但我仍然希望得到解決方案/回复。
我需要在服務器上訪問 CSV 格式的數據,這需要我的令牌被授予訪問權限。我的同事通常使用 Python 訪問此服務。但是,由於我的代碼都在 MATLAB 中,我更喜歡 MATLAB 中的數據,這樣我就可以使用我已經驗證過的現有函數。在 Python 中,我們使用 requests 包如下:
timeseries_url = 'https:// .... /csv'
payload = { 'variable': ['var1','var2'], 'platform_serial' : 'name_of_platform' , 'from' : 'start_time' , 'to' : 'end_time' }
header = {'Authorization': 'Bearer ' + 'authorisation_token'}
# Get the response:
response = requests.get(timeseries_url, headers=header, params=payload)
df = pandas.read_csv(io.StringIO(response.text))
我一直在閱讀關於 HTTP 接口的 MATLAB 文檔。但是,我注意到沒有等效的 get 命令,而只有 send。我認為令牌應該作為 'Credentials'
輸入到 matlab.net.http.HTTPOptions
對像中。同樣,標頭可以是 <代碼>'標題' matlab.net.http.RequestMessage
。另外,我認為payload可以通過'getFields'
獲取。這些假設是否正確?
如何在 MATLAB 中最好地完成這項任務?此外,如何將數據從 CSV 更改為矩陣/單元格以供以後使用?我不認為在這裡使用 csvread
或 readmatrix
是合適的。
我的替代方案是 Python 的 MATLAB 引擎,但我更喜歡簡潔的全 MATLAB 解決方案。
如何在 MATLAB 中最好地完成這項任務?此外,如何將數據從 CSV 更改為矩陣/單元格以供以後使用?我不認為在這裡使用csvread
或 readmatrix
是合適的。 我的替代方案是 Python 的 MATLAB 引擎,但我更喜歡簡潔的全 MATLAB 解決方案。
如何在 MATLAB 中最好地完成這項任務?此外,如何將數據從 CSV 更改為矩陣/單元格以供以後使用?我不認為在這裡使用csvread
或 readmatrix
是合適的。 我的替代方案是 Python 的 MATLAB 引擎,但我更喜歡簡潔的全 MATLAB 解決方案。
參考解法
方法 1:
From the documentation of the Python requests module, it looks like the payload is actually only used to encode the URL.
Here's an example code for MATLAB which you should be able to adapt to your data to submit a successful request:
% URL and token data.
timeseries_url = 'https:// .... /csv';
auth_token = '';
% Structure for the payload.
struct_payload.key1 = 'value1'
struct_payload.key2 = 'value2'
% Find names of fields in struct_payload.
field_names = fieldnames(struct_payload);
% Format url for query.
encoded_url = [timeseries_url '?'];
for i = 1:numel(field_names)
encoded_url = [encoded_url field_names{i} '=' struct_payload.(field_names{i}) '&'];
end
encoded_url(end) = [];
% Create weboptions object with headers.
options = weboptions('HeaderFields',{'Authorization' ['Bearer ' auth_token]});
% Submit webread request.
data = webread(encoded_url, options);
(by Enrico Anderlini、Paolo)