【问题标题】:making a simple GET/POST with url Encoding python使用 url 编码 python 制作一个简单的 GET/POST
【发布时间】:2013-05-01 16:40:15
【问题描述】:

我有一个表单的自定义 url

http://somekey:somemorekey@host.com/getthisfile.json

我尝试了所有方法,但出现错误:

方法一:

from httplib2 import Http
ipdb> from urllib import urlencode
h=Http()
ipdb> resp, content = h.request("3b8138fedf8:1d697a75c7e50@abc.myshopify.com/admin/shop.json")

错误:

No help on =Http()

Got this method from here

方法2: 导入urllib

urllib.urlopen(url).read()

错误:

*** IOError: [Errno url error] unknown url type: '3b8108519e5378'

我猜编码有问题..

我试过了……

ipdb> url.encode('idna')
*** UnicodeError: label empty or too long

有什么方法可以让这个复杂的 url 变得容易调用。

【问题讨论】:

    标签: python http url


    【解决方案1】:

    您正在使用基于 PDB 的调试器而不是交互式 Python 提示符。 h 是 PDB 中的命令。使用! 防止 PDB 尝试将该行解释为命令:

    !h = Http()
    

    urllib 要求您传递一个完全限定的 URL;您的网址缺少方案:

    urllib.urlopen('http://' + url).read()
    

    您的 URL 似乎没有在域名中使用任何国际字符,因此您不需要使用 IDNA 编码。

    您可能想查看第 3 方 requests library;它使与 HTTP 服务器的交互变得更加简单直接:

    import requests
    r = requests.get('http://abc.myshopify.com/admin/shop.json', auth=("3b8138fedf8", "1d697a75c7e50"))
    data = r.json()  # interpret the response as JSON data.
    

    【讨论】:

      【解决方案2】:

      当前用于 Python 的事实上的 HTTP 库是 Requests

      import requests
      response = requests.get(
        "http://abc.myshopify.com/admin/shop.json",
        auth=("3b8138fedf8", "1d697a75c7e50")
      )
      response.raise_for_status()  # Raise an exception if HTTP error occurs
      print response.content  # Do something with the content.
      

      【讨论】:

      • InvalidURL at / URL 的标签无效。
      猜你喜欢
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2021-03-11
      • 1970-01-01
      • 2021-11-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多