Error using webread and websave to retrieve JSON data from RESTful web service

version '9.7.0.1247435 (R2019b) Update 2'
I am attempting to read data returned from a web service using either webread or websave. The relevant MATLAB code is as follows:
service_url = "https://webservice.testserver.com/results?format=json";
opts = weboptions("HeaderFields", {'Authorization' api_token});
results_resp = webread(service_url, opts);
The error returned is:
Error using matlab.internal.webservices.HTTPConnector/copyContentToFile (line 412)
The server returned the status 400 with message "Bad Request" in response to the request to URL
Error in readContentFromWebService (line 62)
copyContentToFile(connection, filename);
Error in webread (line 125)
[varargout{1:nargout}] = readContentFromWebService(connection, options);
I have also tried websave, with the code above becoming:
service_url = "https://webservice.testserver.com/results?format=json";
opts = weboptions("HeaderFields", {'Authorization' api_token});
results_resp = websave("the_json_file.txt", service_url, opts);
The error returned is similar:
Error using matlab.internal.webservices.HTTPConnector/copyContentToFile (line 412)
The server returned the status 400 with message "Bad Request" in response to the request to URL
Error in websave (line 107)
copyContentToFile(connection, filename);
I note that the following command using curl on the Linux command line works fine.
curl -H "Authorization: api_token" -L "https://webservice.testserver.com?format=json"

Réponses (1)

As a workaround, I was able to solve this by using the Python requests module - calling this from MATLAB using the following:
service_url = "https://webservice.testserver.com/results";
import py.requests.get
headers = py.dict(pyargs('Authorization', api_token));
params = py.tuple({'format', 'json'});
results_resp = get(service_url, pyargs('headers', headers, 'params', params));
json_data = jsondecode(native2unicode(results_resp.content));
The last line converts the Python returned response results_resp.content into a MATLAB struct, for the JSON data returned in my case, for parsing.

Produits

Version

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by