首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Google API和请求来缩短URL?

如何使用Google API和请求来缩短URL?
EN

Stack Overflow用户
提问于 2017-04-14 09:20:11
回答 3查看 1.6K关注 0票数 1

我试图使用Google API来缩短网址,但只使用了requests模块。

代码如下所示:

代码语言:javascript
复制
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):
  payload = {'longUrl': url, "key":Key}
  r = requests.post(api, params=payload)

print(r.text)

当我运行goo_shorten_url时,它返回:

代码语言:javascript
复制
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required",
    "locationType": "parameter",
    "location": "resource.longUrl"
   }

  ],
  "code": 400,
  "message": "Required"
 }

但是longUrl参数就在那里!

我做错了什么?

EN

回答 3

Stack Overflow用户

发布于 2017-04-14 10:03:55

请先确认Google API Console开启了urlshortener接口v1。

Content-Type需要作为标头。请使用data作为请求参数。修改后的样本如下。

修改样本:

代码语言:javascript
复制
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。在使用访问令牌的情况下,示例脚本如下所示。

示例脚本:

代码语言:javascript
复制
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)

结果:

代码语言:javascript
复制
{
 "kind": "urlshortener#url",
 "id": "https://goo.gl/#####",
 "longUrl": "http://www.google.com/"
}

增加了1个:

在使用tinyurl.com的情况下

代码语言:javascript
复制
import requests

URL = "http://www.google.com/"
r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
print(r.text)

增加了2 :

如何使用Python快速入门

您可以使用Python Quickstart。如果您没有"google-api-python-client",请安装它。安装完成后,请从步骤3:设置示例中复制粘贴一个示例脚本,并将其创建为python脚本。修改点如下两部分。

1.作用域

之前的 :

代码语言:javascript
复制
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

之后的

代码语言:javascript
复制
SCOPES = 'https://www.googleapis.com/auth/urlshortener'

2.脚本

之前的 :

代码语言:javascript
复制
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']))

之后的

代码语言:javascript
复制
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)

完成上述修改后,请执行示例脚本。您可以获得简短的URL。

票数 1
EN

Stack Overflow用户

发布于 2017-04-15 00:44:39

我确信,一个人不能只使用请求来使用google api来缩短url。

下面我写了我最终得到的解决方案,

它可以工作,但它使用google api,这是可以的,但我找不到很多关于它的文档或示例(不像我想要的那么多)。

要运行代码,请记住首先使用pip install google-api-python-client安装google api for python,然后:

代码语言:javascript
复制
import json

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

scopes = ['https://www.googleapis.com/auth/urlshortener']

path_to_json = "PATH_TO_JSON" 
#Get the JSON file from Google Api [Website]
(https://console.developers.google.com/apis/credentials), then:
# 1. Click on Create Credentials. 
# 2. Select "SERVICE ACCOUNT KEY". 
# 3. Create or select a Service Account and 
# 4. save the JSON file.   

credentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_json, scopes)

short = build("urlshortener", "v1",credentials=credentials)

request = short.url().insert(body={"longUrl":"www.google.com"})
print(request.execute())

这是我从Google's Manual Page改编的。

它必须如此复杂(至少比我一开始预期的要复杂)的原因是为了避免需要用户(在本例中是我)按下按钮(以确认我可以使用我的信息)的OAuth2身份验证。

票数 0
EN

Stack Overflow用户

发布于 2017-04-15 15:32:06

由于问题不是很清楚,这个答案分为4个部分。

使用以下方式缩短URL:

1. API密钥。

2.访问令牌

3.服务帐号

4.使用TinyUrl更简单的解决方案。

API密钥

请先确认Google API Console开启了urlshortener接口v1。

Content-Type需要作为标头。请使用data作为请求参数。修改后的样本如下。

(无论API手册上怎么说,似乎都不起作用)。

修改样本:

代码语言:javascript
复制
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。在使用访问令牌的情况下,示例脚本如下所示。

Stackoverflow中的这个答案展示了如何获取访问令牌:Link

示例脚本:

代码语言:javascript
复制
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)

结果:

代码语言:javascript
复制
{
 "kind": "urlshortener#url",
 "id": "https://goo.gl/#####",
 "longUrl": "http://www.google.com/"
}

使用服务帐户的

为了避免用户需要接受OAuth身份验证(通过弹出屏幕等),有一种解决方案使用服务帐户在机器之间使用身份验证(如另一个建议的答案中所提到的)。

要运行这部分代码,请记住首先使用pip install google-api-python-client安装google api for python,然后:

代码语言:javascript
复制
import json

from oauth2client.service_account import ServiceAccountCredentials
from apiclient.discovery import build

scopes = ['https://www.googleapis.com/auth/urlshortener']

path_to_json = "PATH_TO_JSON" 
#Get the JSON file from Google Api [Website]
(https://console.developers.google.com/apis/credentials), then:
# 1. Click on Create Credentials. 
# 2. Select "SERVICE ACCOUNT KEY". 
# 3. Create or select a Service Account and 
# 4. save the JSON file.   

credentials = ServiceAccountCredentials.from_json_keyfile_name(path_to_json, scopes)

short = build("urlshortener", "v1",credentials=credentials)

request = short.url().insert(body={"longUrl":"www.google.com"})
print(request.execute())

改编自Google's Manual Page

更简单:

在使用tinyurl.com的情况下

代码语言:javascript
复制
import requests

URL = "http://www.google.com/"
r = requests.get("http://tinyurl.com/" + "api-create.php?url=" + URL)
print(r.text)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43403954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档