首先,请确认在Google API Console中启用了“urlshortener api v1” 。
Content-Type
需要作为标题。请data
作为请求参数使用。修改后的样本如下。
修改样本:
import json
import requests
Key = "" # found in https://developers.google.com/url-shortener/v1/getting_started#APIKey
api = "https://www.googleapis.com/urlshortener/v1/url"
target = "http://www.google.com/"
def goo_shorten_url(url=target):
headers = {"Content-Type": "application/json"}
payload = {'longUrl': url, "key":Key}
r = requests.post(api, headers=headers, data=json.dumps(payload))
print(r.text)
如果上述脚本不起作用,请使用访问令牌。范围是https://www.googleapis.com/auth/urlshortener
。在使用访问令牌的情况下,示例脚本如下。
示例脚本:
import json
import requests
headers = {
"Authorization": "Bearer " + "access token",
"Content-Type": "application/json"
}
payload = {"longUrl": "http://www.google.com/"}
r = requests.post(
"https://www.googleapis.com/urlshortener/v1/url",
headers=headers,
data=json.dumps(payload)
)
print(r.text)
结果 :
{
"kind": "urlshortener#url",
"id": "https://goo.gl/#####",
"longUrl": "http://www.google.com/"
}
添加了 1:
在使用的情况下tinyurl.com
import requests
URL = "http://www.google.com/"
r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
print(r.text)
添加 2:
如何使用 Python 快速入门
您可以使用Python 快速入门。如果您没有“google-api-python-client”,请安装它。安装后,请复制粘贴“步骤 3:设置示例”中的示例脚本,并将其创建为 python 脚本。修改点如下2部分。
一、范围
前 :
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
后 :
SCOPES = 'https://www.googleapis.com/auth/urlshortener'
2. 脚本
前 :
def main():
"""Shows basic usage of the Google Drive API.
Creates a Google Drive API service object and outputs the names and IDs
for up to 10 files.
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
results = service.files().list(
pageSize=10,fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1})'.format(item['name'], item['id']))
后 :
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('urlshortener', 'v1', http=http)
resp = service.url().insert(body={'longUrl': 'http://www.google.com/'}).execute()
print(resp)
完成以上修改后,请执行示例脚本。您可以获得短网址。