Call Google Tiny URL API in MATLAB

15 次查看(过去 30 天)
Kevin
Kevin 2016-6-10
编辑: Kevin 2018-1-21
Hi everyone,
I am trying to call Google URL Shortener API https://developers.google.com/url-shortener/v1/getting_started#actions in MATLAB to shorten an URL. I know that I can go to https://goo.gl/ and manually paste the long URL into the text box. But I am wondering if I can do that programatically in MATLAB.
I know very little about web programming and this is as far as I can get,
options = weboptions('RequestMethod','post');
data = webread('https://www.googleapis.com/urlshortener/v1/url', 'longUrl', 'http://www.google.com/', options)
Error using readContentFromWebService (line 45)
The server returned the status 400 with message "Bad Request" in response to the request to URL https://www.googleapis.com/urlshortener/v1/url.
Error in webread (line 122)
[varargout{1:nargout}] = readContentFromWebService(connection, options);

回答(1 个)

Chi
Chi 2018-1-19
First, you should have a URL shortener API key. It can be generated in the Google Credentials page .
Then, the matlab code:
url='https://www.googleapis.com/urlshortener/v1/url?key={yours}';
options = weboptions('RequestMethod','post', 'MediaType','application/json');
Body = struct('longUrl', 'http://www.google.com/');
response = webwrite(url, Body, options);
  1 个评论
Kevin
Kevin 2018-1-19
编辑:Kevin 2018-1-21
Hi Chi,
Thank you very much for your suggestion. I followed your instruction to click the link "Google Credentials page" to create the key. I got the key and tried out the following MATLAB code. But I got error message from Google.
key = 'this_is_not_the_real_key';
url = ['https://www.googleapis.com/urlshortener/v1/url?key=', key];
options = weboptions('RequestMethod', 'post', 'MediaType', 'application/json');
Body = struct('longUrl', 'http://www.google.com/');
response = webwrite(url, Body, options);
Error using readContentFromWebService (line 46)
The server returned the status 403 with message "Forbidden" in response
to the request to URL https://www.googleapis.com/urlshortener/v1/url?
key=this_is_not_the_real_key.
Seems to me that the key (that I copy-and-paste from Google) does not work. I already set the key to "unrestricted" in Google page.
Kevin

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Google 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by