自己练手的一个小项目,使用Python3中自带的网络库urllib,发送post请求,请求参数为json字符串。
url = 'http://xxxx.com'
params = {
a:'1',
b:'2'
}
params = json.dumps(params)
headers = {'Accept-Charset': 'utf-8', 'Content-Type': 'application/json'}
req = urllib.request.Request(url=path, data=params, headers=headers, method='POST')
response = urllib.request.urlopen(req).read()
上面写法报错
POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str
因为urllib的Request参数不能传递字符串。
查询资料后修改为:
url = 'http://xxxx.com'
params = {
a:'1',
b:'2'
}
params = json.dumps(params)
headers = {'Accept-Charset': 'utf-8', 'Content-Type': 'application/json'}
//添加encode编码
params = urllib.parse.quote_plus(es_params).encode(encoding='utf-8')
req = urllib.request.Request(url=path, data=params, headers=headers, method='POST')
response = urllib.request.urlopen(req).read()
上面写法服务端报错500,参数传递的有问题。
查询资料后修改为:
url = 'http://xxxx.com'
params = {
a:'1',
b:'2'
}
params = json.dumps(params)
headers = {'Accept-Charset': 'utf-8', 'Content-Type': 'application/json'}
//用bytes函数转换为字节
params = bytes(es_params, 'utf8')
req = urllib.request.Request(url=path, data=params, headers=headers, method='POST')
response = urllib.request.urlopen(req).read()
大功告成。。。