使用url编码python制作一个简单的GET/POST

2024-09-29 23:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有表单的自定义url

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

我试了一路,但还是出错了:

方法1:

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

错误:

^{pr2}$

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得到轻松的调用。在


Tags: 方法fromimportcomjsonhttphosturl
2条回答

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

!h = Http()

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

^{pr2}$

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

您可能需要了解第三方^{} 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.

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.

相关问题 更多 >

    热门问题