MATLAB使用HTTP通信的两种方法

发布时间 2023-10-10 20:16:25作者: C_noized

1.使用sendRequest函数

sendRequest函数的定义由MATLAB官方帮助文档给出:

function response = sendRequest(uri,request)

% uri: matlab.net.URI
% request: matlab.net.http.RequestMessage
% response: matlab.net.http.ResponseMessage

% matlab.net.http.HTTPOptions persists across requests to reuse  previous
% Credentials in it for subsequent authentications
persistent options 

% infos is a containers.Map object where: 
%    key is uri.Host; 
%    value is "info" struct containing:
%        cookies: vector of matlab.net.http.Cookie or empty
%        uri: target matlab.net.URI if redirect, or empty
persistent infos

if isempty(options)
    options = matlab.net.http.HTTPOptions('ConnectTimeout',20);
end

if isempty(infos)
    infos = containers.Map;
end
host = string(uri.Host); % get Host from URI
try
    % get info struct for host in map
    info = infos(host);
    if ~isempty(info.uri)
        % If it has a uri field, it means a redirect previously
        % took place, so replace requested URI with redirect URI.
        uri = info.uri;
    end
    if ~isempty(info.cookies)
        % If it has cookies, it means we previously received cookies from this host.
        % Add Cookie header field containing all of them.
        request = request.addFields(matlab.net.http.field.CookieField(info.cookies));
    end
catch
    % no previous redirect or cookies for this host
    info = [];
end

% Send request and get response and history of transaction.
[response, ~, history] = request.send(uri, options);
if response.StatusCode ~= matlab.net.http.StatusCode.OK
    return
end

% Get the Set-Cookie header fields from response message in
% each history record and save them in the map.
arrayfun(@addCookies, history)

% If the last URI in the history is different from the URI sent in the original 
% request, then this was a redirect. Save the new target URI in the host info struct.
targetURI = history(end).URI;
if ~isequal(targetURI, uri)
    if isempty(info)
        % no previous info for this host in map, create new one
        infos(char(host)) = struct('cookies',[],'uri',targetURI);
    else
        % change URI in info for this host and put it back in map
        info.uri = targetURI;
        infos(char(host)) = info;
    end
end

    function addCookies(record)
        % Add cookies in Response message in history record
        % to the map entry for the host to which the request was directed.
        %
        ahost = record.URI.Host; % the host the request was sent to
        cookieFields = record.Response.getFields('Set-Cookie');
        if isempty(cookieFields)
            return
        end
        cookieData = cookieFields.convert(); % get array of Set-Cookie structs
        cookies = [cookieData.Cookie]; % get array of Cookies from all structs
        try
            % If info for this host was already in the map, add its cookies to it.
            ainfo = infos(ahost);
            ainfo.cookies = [ainfo.cookies cookies];
            infos(char(ahost)) = ainfo;
        catch
            % Not yet in map, so add new info struct.
            infos(char(ahost)) = struct('cookies',cookies,'uri',[]);
        end
    end
end

然后我们生成一个默认请求:

request = matlab.net.http.RequestMessage();

生成一个uri:

uri = matlab.net.URI('https://www.baidu.com');

使用sendRequest:

response = sendRequest(uri,request)

得到的response结果:

response = 

  ResponseMessage 属性:

    StatusLine: 'HTTP/1.1 200 OK'
    StatusCode: OK
        Header: [1×17 matlab.net.http.HeaderField]
          Body: [1×1 matlab.net.http.MessageBody]
     Completed: 0

2.使用webread读取内容

要读取的网页内容:
image

webread两行搞定:

httpsUrl = 'http://localhost:10120/terminated-service/terminated/exec?para=load(%22/home/meow/Desktop/oceanScript.ocn%22)';
data = webread(httpsUrl,weboptions('Timeout',60));

返回值data:

data = 

  struct with fields:

     code: '10000'
      msg: '成功'
    value: 't'

关于webread的第二个参数,webread函数的官方手册是这样说明的:

WEBREAD Read content from RESTful web service

  Syntax
  ------
  DATA = WEBREAD(URL)
  DATA = WEBREAD(URL,QueryName1,QueryValue1, ...)
  DATA = WEBREAD(__,OPTIONS)
  [DATA1,__] = WEBREAD(__)

  Description
  ------------
  DATA = WEBREAD(URL) reads content from the web service specified by the
  string URL and returns the content in DATA. WEBREAD sets HTTP request
  parameters with the default property values of WEBOPTIONS and uses the
  HTTP GET method to read content from URL.

  DATA = WEBREAD(URL,QueryName1,QueryValue1,...) appends additional RESTful
  web service query parameters, specified by QueryName1, QueryValue1, ..., to
  URL. These name,value pair arguments set query parameters in an HTTP GET
  operation. The parameters supported by a web service are defined in the
  service's documentation. WEBREAD adds parameters to URL using the
  "&name=value" construct. However, if URL does not contain a "?" character,
  then WEBREAD adds the first name, value pair as "?name=value". WEBREAD still
  adds all following parameters as "&name=value". Numeric and logical values
  are converted to strings using NUM2STR. Nonscalar values are encoded as
  specified by the default ArrayFormat property of WEBOPTIONS.

  DATA = WEBREAD(__, OPTIONS) sets HTTP request parameters with the property
  values of the scalar WEBOPTIONS object OPTIONS. Set the RequestMethod
  property of OPTIONS to 'post' or some other method if you need to use a
  method other than GET when reading data from a RESTful web service.
  Changing the RequestMethod does not affect where the query parameters are
  placed: they always are appended to the URL. To place parameters in the
  body of the message, use WEBWRITE.  

  [DATA1, __] = WEBREAD(__) returns multiple data values from the web
  service if the data content is an indexed image or audio data, or if
  you set options.ContentReader and your content reader returns multiple
  outputs.

  Input Arguments
  ---------------

  Name  Description                                     Data Type
  ----  --------------------                            ---------
  URL   Web address of content including the            string
        transfer protocol, http or https. 
        The URL is automatically encoded.

  QueryName
        Name of additional web service parameter        string
        to append to URL.

  QueryValue 
        Value of additional web service parameter       string; vector of
        to append to URL. If you specify a datetime     numeric, logical
        you must specify its Format property as         or datetime; 2-D 
        expected by the web service.  If it is a        array of char; or
        non-scalar vector or cell vector, or char       cell array containing
        array with more than one row, the value is      strings or numeric,
        processed according to the ArrayFormat property logical or datetime
        of WEBOPTIONS.                                  scalars

  OPTIONS
        Other options used to connect to web            scalar WEBOPTIONS
        service.                                        object

  % Example 1
  % ---------
  % Read the HTML page on the MATLAB(R) Central File Exchange that lists 
  % submissions for sensor-data-acquisition.
  url = 'https://www.mathworks.com/matlabcentral/fileexchange';
  searchTerm = 'sensor-data-acquisition';
  html = webread(url,'term',searchTerm)

  % Example 2
  % ---------
  % Read USA average historical temperature data based on gridded
  % climatologies from the Climate Research Unit and provided by the
  % World Bank web service. More information on the data set may be found
  % at http://data.worldbank.org/developers/climate-data-api
  % The service returns data formatted as JSON objects.
  % webread converts homogeneous JSON objects to a structure array.
  api = 'http://climatedataapi.worldbank.org/climateweb/rest/v1/';
  url = [api 'country/cru/tas/year/USA'];
  S = webread(url)

  % Plot the average temperature per year. 
  % Convert temperatures and years to numeric arrays. 
  % Convert years to a datetime array for ease of plotting.
  temperatures = [S.data];
  years = [S.year];
  month = 1;
  day = 1;
  yearsToPlot = datetime(years,month,day);
  figure
  plot(yearsToPlot,temperatures);
  minyear = num2str(min(years));
  maxyear = num2str(max(years));
  attribution = 'World Bank: Historical Data: Climate Research Unit';
  title({['USA Average Temperature ',minyear,'-',maxyear], attribution});
  xlabel Year
  ylabel 'Temperature (^{\circ}C)'

  % Read JSON data from the World Bank web service as text. 
  options = weboptions('ContentType','text');
  textData = webread(url,options)

  See also AUDIOREAD, DATETIME, IMREAD, READTABLE, JSONDECODE, WEBOPTIONS, WEBWRITE, 
           WEBSAVE, XMLREAD, WEBOPTIONS.ArrayFormat

Copyright 2014-2017 The MathWorks, Inc.