Matlab发送HTTP请求: 使用M文件自定义函数
想要在Matlab中便捷地发送HTTP请求? 使用.m文件定义自定义函数是最佳选择! 下面是一个示例, 演示如何创建一个名为sendHTTPRequest的函数, 用于发送HTTP请求:
function response = sendHTTPRequest(url, method, headers, body)
% 创建一个Matlab内置的HTTP请求对象
options = weboptions('RequestMethod', method, 'HeaderFields', headers, 'MediaType', 'application/json');
% 发送HTTP请求并获取响应
response = webread(url, body, options);
end
将上述代码保存为sendHTTPRequest.m文件, 即可在Matlab中调用该函数发送HTTP请求, 如下所示:
url = 'https://api.example.com/data';
method = 'GET';
headers = {'Content-Type', 'application/json'};
body = '';
response = sendHTTPRequest(url, method, headers, body);
disp(response);
在示例中, sendHTTPRequest函数接受URL, 请求方法, 请求头和请求体作为参数, 并返回响应结果. 你可以根据实际需求自定义函数的参数和返回值类型, 灵活地发送各种HTTP请求.
原文地址: https://www.cveoy.top/t/topic/bIi0 著作权归作者所有。请勿转载和采集!