【问题标题】:how to use Google Shortener API with Python如何在 Python 中使用 Google Shortener API
【发布时间】:2013-06-28 04:45:58
【问题描述】:

我想写一个应用来缩短网址。这是我的代码:

import urllib, urllib2
import json
def goo_shorten_url(url):
    post_url = 'https://www.googleapis.com/urlshortener/v1/url'
    postdata = urllib.urlencode({'longUrl':url})
    headers = {'Content-Type':'application/json'}
    req = urllib2.Request(
        post_url,
        postdata,
        headers
        )
    ret = urllib2.urlopen(req).read()
    return json.loads(ret)['id']

当我运行代码以获取一个小 URL 时,它会引发异常:urllib2.HTTPError: HTTP Error 400: Bad Requests。 这段代码有什么问题?

【问题讨论】:

    标签: python google-api google-url-shortener


    【解决方案1】:

    我尝试了你的代码,也不能让它工作,所以我用requests写了它:

    import requests
    import json
    
    def goo_shorten_url(url):
        post_url = 'https://www.googleapis.com/urlshortener/v1/url'
        payload = {'longUrl': url}
        headers = {'content-type': 'application/json'}
        r = requests.post(post_url, data=json.dumps(payload), headers=headers)
        print r.text
    

    编辑:使用 urllib 的代码:

    def goo_shorten_url(url):
        post_url = 'https://www.googleapis.com/urlshortener/v1/url'
        postdata = {'longUrl':url}
        headers = {'Content-Type':'application/json'}
        req = urllib2.Request(
            post_url,
            json.dumps(postdata),
            headers
        )
        ret = urllib2.urlopen(req).read()
        print ret
        return json.loads(ret)['id']
    

    【讨论】:

    • 感谢您的回复。urllib 和 urllib2 的 API 真的很丑。实际上,我已经编写了带有请求的应用程序,它也可以工作,但是为什么我要用 json.dumps 替换 urllib.urlencode 呢?
    • 因为urlencode 传递了由 & 分隔的 key:value,而 google API 期望的是一个类似 json 的数据 {key:value}。 [urlencode] (docs.python.org/2/library/urllib.html#urllib.urlencode)
    • 在你的回答中我找到了我的解决方案:我在 requests.post() 中使用 'params' 而不是 'data'
    • @eugene 你可以在这里找到如何获取密钥:developers.google.com/url-shortener/v1/getting_started#APIKey
    【解决方案2】:

    我知道这个问题很老,但在 Google 上却很高。

    要尝试的另一件事是 pyshorteners 库,它的实现非常简单。

    这是一个链接:

    https://pypi.python.org/pypi/pyshorteners

    【讨论】:

      【解决方案3】:

      使用 api 密钥:

      import requests
      import json
      
      def shorten_url(url):
          post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(API_KEY)
          payload = {'longUrl': url}
          headers = {'content-type': 'application/json'}
          r = requests.post(post_url, data=json.dumps(payload), headers=headers)
          return r.json()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多