Main Content

webread

Read content from RESTful web service

Description

example

data= webread(url)reads content from the web service specified byurland returns the content indata.

The web service provides aRESTfulthat returns data formatted as an internet media type such as JSON, XML, image, or text.

example

data= webread(url,QueryName1,QueryValue1,...,QueryNameN,QueryValueN)appends query parameters tourl, as specified by one or more pairs of name-value arguments. To put a query into the body of the message, usewebwrite. The web service defines the query parameters.

example

data= webread(___,options)adds other HTTP request options, specified by theweboptionsobjectoptions. You can use this syntax with any of the input arguments of the previous syntaxes.

To return data as a specific output type, specify theContentTypeproperty ofoptions.

To read content with a function, specify theContentReaderproperty ofoptionsas a handle to the function.webreaddownloads data from a web service and reads the data with the specified function:

  • If you specify a handle to a function that returns multiple output arguments,webreadreturns all output arguments.

  • If you specify a handle to a function that returns no output argument (such as Image Processing Toolbox™ function@implayfor video files),webreadreturns no output argument.

[data,colormap,alpha] = webread(___)reads an image from the web service specified byurland returns the image indata. You can use the previous syntaxes to return the image only. Use this syntax to return the colormap and alpha channels associated with the image.

webreadreturns an image when the HTTP response has aContent-Typeheader field that specifies an image media type and ifimreadsupports the image format. For supported image formats, seeSupported File Formats for Import and Export.

[data,Fs] = webread(___)reads audio data from the web service specified byurland returns the audio data indata. You can use the previous syntaxes to return the audio data only. Use this syntax to return the sample rate of the audio data in hertz.

webreadreturns audio data when the HTTP response has aContent-Typeheader field that specifies an audio media type and ifaudioreadsupports the audio format. For supported audio formats, seeSupported File Formats for Import and Export.

Examples

collapse all

This example shows how to read an image from a website and display it.

Read Image Data

httpsUrl ='https://requestserver.mathworks.com'; imageUrl = strcat(httpsUrl,'/assets/computerVision.jpg'); rgb = webread(imageUrl); whosrgb
Name Size Bytes Class Attributes rgb 360x640x3 691200 uint8

Resize and Display Image

rgb = imresize(rgb, 0.6); imshow(rgb)

This example shows how to read temperatures from acsvdata file.

Read Data From CSV File

httpsUrl ="https://requestserver.mathworks.com"; dataUrl = strcat(httpsUrl,"/assets/weatherStation.csv"); data = webread(dataUrl); time = [data.Time]; temp = [data.TempF];

Display Temperature Plot

plot(time, temp) xlabel("Time") ylabel("Temperature (Farenheit)") title("Temperature Over Time"); axispadded

This example shows how to select a record using query parameters.

View Employee Database Structure

Display the fields of databaseemployee.

httpsUrl ="https://requestserver.mathworks.com"; employeeUrl = strcat(httpsUrl,"/employee"); fieldnames(webread(employeeUrl))
ans =6×1 cell{'id' } {'firstName' } {'lastName' } {'occupation'} {'age' } {'city' }

Select Employee byfirstNameandlastName

jSmith = webread(employeeUrl,"firstName","John","lastName","Smith"); disp(jSmith);
id: 1 firstName: 'John' lastName: 'Smith' occupation: 'Software Engineer' age: '32' city: 'Boston'

This example shows how to return data as a specific type.

Read Data

httpUrl ="http://requestserver.mathworks.com"; employeeUrl = strcat(httpUrl,"/employee");

Return Record as Character Array

Create aweboptionsobject and set itsContentTypeto'text'. Thewebreadfunction converts the JSON object to a character array.

options = weboptions("ContentType","text"); sBrown = webread(employeeUrl,"firstName","Sarah", options); disp(sBrown)
[{"id":2,"firstName":"Sarah","lastName":"Brown","occupation":"Software Engineer","age":"28","city":"New York"}]

Input Arguments

collapse all

URL to a web service, specified as a character vector or string scalar. Include the transfer protocol. Onlyhttpandhttpsare supported. The web service implements a RESTful interface. SeeRESTfulfor more information.

Example:webread('//www.tianjin-qmedu.com/matlabcentral')reads the web page and returns its HTML as a character array.

Web service query parameters, specified as one or more pairs of name-value arguments. AQueryNameargument must specify the name of a query parameter, as a character vector or string scalar. AQueryValueargument must be a character vector, a string scalar, or a numeric, logical, ordatetimevalue that specifies the value of the query parameter. Numeric, logical, anddatetimevalues can be in arrays. The web service defines name-value pairs that it accepts as part of a request.

When you specifyQueryValueas adatetimeobject, you must specify itsFormatproperty so that it is consistent with the format required by the web service. If theFormatproperty includes a time zone or offset, and thedatetimeobject is not zoned, thenwebreadspecifies'Local'as the time zone.

WhenQueryValuecontains multiple values in an array, you might need to specify theArrayFormat财产的weboptionsobject to form-encode the array as specified by the web service.

Example:webread('//www.tianjin-qmedu.com/matlabcentral/fileexchange/','term','webread')retrieves a list of files uploaded to the File Exchange that contain the wordwebread.

Additional HTTP request options, specified as aweboptionsobject.

You can specify theContentType财产的weboptionsobject, and pass the object as an input argument towebread. Thenwebreadreturnsdataas that type of output. The table lists the valid content types you can specify in aweboptionsobject.

ContentTypeSpecifier

Output Type

'auto'(default)

Output type automatically determined based on content type specified by the server.

'text'

Character vector for content types:

text/plain
text/html
text/xml
application/xml
application/javascript
application/x-javascript
application/x-www-form-urlencoded

If a web service returns a MATLAB®file with a.mextension, the function returns its content as a character vector.

'image'

Numeric or logical matrix forimage/formatcontent. If the first output argument is an indexed image, the second output argument is the colormap, and the third output argument is the alpha channel.

For supported image formats, seeSupported File Formats for Import and Export.

'audio'

Numeric matrix foraudio/formatcontent with numeric scalar sampling rate as a second output argument.

For supported audio formats, seeSupported File Formats for Import and Export.

'binary'

uint8column vector for binary content (that is, content not to be treated as typechar).

'table'

Scalar table object for spreadsheet and CSV (text/csv) content.

'json'

char, numeric, logical, structure, or cell array, forapplication/jsoncontent.

'xmldom'

Java®Document Object Model (DOM) node fortext/xmlorapplication/xmlcontent. If not specified, the function returns XML content as a character vector.

'raw'

charcolumn vector for'text','xmldom', and'json'content. The function returns any other content type as auint8column vector.

Seeweboptionsfor all request options that areweboptionsproperties.

Output Arguments

collapse all

Content read from a web service, returned as a scalar, array, structure, or table.

Colormap associated with an indexed image, returned as a numeric array.

Alpha channels associated with an indexed image, returned as a numeric array.

Sample rate of audio data in hertz, returned as a positive numeric scalar.

More About

collapse all

RESTful

RESTmeansrepresentational state transfer常见的的一种建筑风格的web服务。RESTful interfaces provide standard HTTP methods such as GET, PUT, POST, or DELETE.

Tips

  • For functionality not supported by the RESTful web services functions, see theUse HTTP with MATLAB.

  • webreadsupports HTTP GET and POST methods. Many web services provide both GET and POST methods to request data. To send an HTTP POST request, specify theRequestMethodproperty ofoptionsas'post'. However,webreadputs query options into theurl, not in the body of the request message. To put a query into the body, usewebwrite.

  • For HTTP POST requests, thewebreadfunction supports only theapplication/x-www-form-urlencodedmedia type. To send a POST request with content of any other internet media type, usewebwrite.

  • This function does not examine the document contents to determine how to process it. For example, HTML and XML documents often contain atag that specifies the document character encoding. If the encoding is different from the defaultwebreadencoding, then specify the correctCharacterEncodingoption inweboptions.

  • To specify proxy server settings, seeProxy Server Authentication.

Version History

Introduced in R2014b