在Python中使用urllib vs请求的HTTP Post
我正在尝试使用web api,它需要HTTP中的Post字段。web是带有python3.6.2的https。 我已尝试urllib.request.urlopen,但响应无效 urllib.error.HTTPError:HTTP错误403:禁止 以下是我使用的代码:在Python中使用urllib vs请求的HTTP Post,python,Python,我正在尝试使用web api,它需要HTTP中的Post字段。web是带有python3.6.2的https。 我已尝试urllib.request.urlopen,但响应无效 urllib.error.HTTPError:HTTP错误403:禁止 以下是我使用的代码: from urllib.parse import urlencode from urllib.request import Request, urlopen from hashlib import sha256 import t
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from hashlib import sha256
import time
key = 'xxxxxxxxxx'
secret_key = 'yyyyyyyyyyyy'
nonce = int(time.time())
signature = sha256((key + str(nonce) + secret_key).encode()).hexdigest()
url = "https://xxxxx/api/"
post_fields = {'key': key, 'nonce': nonce,
'signature': signature}
request = Request(url, data=urlencode(post_fields).encode())
response = urlopen(request).read().decode()
但是,我尝试了以下代码:
import requests
from hashlib import sha256
import time
key = 'xxxxxxxxxx'
secret_key = 'yyyyyyyyyyyy'
nonce = int(time.time())
signature = sha256((key + str(nonce) + secret_key).encode()).hexdigest()
url = "https://xxxxx/api/"
post_fields = {'key': key, 'nonce': nonce,
'signature': signature}
response = requests.post(url, post_fields)
它是有效的。
我真的很想知道不同之处,因为urllib.request可以在指定数据参数时发送post请求。两段代码都发送正确的post请求。它们之间的唯一区别将是发送的标题。除了完全相同的标题外,urllib.request将发送:
Accept-Encoding: identity
User-Agent: Python-urllib/3.6
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: python-requests/2.18.1
而请求将发送:
Accept-Encoding: identity
User-Agent: Python-urllib/3.6
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: python-requests/2.18.1
您必须尝试向urllib.request代码添加和更改头,看看这些是否重要
你可以随时使用http://httpbin.org/post 作为URL查看您发布的信息;该服务将接收到的内容作为JSON对象回显。有关更多信息,请参阅。我已更改为关键参数,只是不想显示真正的变量名。我将尝试更改urllib.request发送的头。谢谢你的回答。