我正在使用Python 2.7和Python 3向远程服务器发出POST请求,并且在每种情况下都会得到不同的响应。问题可能是每个请求中的数据如何编码?我在2.7中所做的Python 3等效功能是什么?
// Python 2.7
data = {'username':'test'}
data = urllib.urlencode(data)
print(data)
req = urllib2.Request(base_link + 'inf.cgi', data, headers)
response = urllib2.urlopen(req)
mypage = response.read()
用户=测试
// Python 3
data = {'username':'test'}
data = urllib.parse.urlencode(data).encode("utf-8")
print(data)
base_link = 'http://tax1.co.monmouth.nj.us/cgi-bin/'
# Make HTTP request
request = urllib.request.Request(url, data, headers)
mypage = urllib.request.urlopen(request).read()
b'user = test'
尝试此操作而不对数据进行编码:
data = urllib.parse.urlencode(data)
提供与2.7类似的输出:
用户=测试
但是在发出POST请求时会导致错误:'TypeError:POST数据应为字节,字节可迭代或文件对象。它不能为str。'
您正在寻找urllib.parse
。这是我使用的代码示例。
address = urllib.parse.quote(address, safe='/:=?&', encoding="utf-8", errors="strict")
address = urllib.request.urlopen(address).read().decode('utf8')