【Python】python3实现post

网上python2和python3混乱,写一段简单代码入坑无数,自己记录一下

1.使用decode解决显示中文乱码问题
2.使用open方法的wb参数,可以直接把byte写入文件

import urllib
import urllib.request
import json

url = 'https://xxxxxx.com/getAllInfo'
params = {
    
    
    'a':'1',
    'b':'2'
}

params = json.dumps(params)
headers = {
    
    'Accept-Charset': 'utf-8', 'Content-Type': 'application/json'}
#用bytes函数转换为字节
params = bytes(params, 'utf8')

req = urllib.request.Request(url=url, data=params, headers=headers, method='POST')
response = urllib.request.urlopen(req).read()
print(response.decode('utf-8'))

#写入json文件
fo = open("getAllInfo.json", "wb")
fo.write(response)
 
# 关闭打开的文件
fo.close()

我的博客

猜你喜欢

转载自blog.csdn.net/hifhf/article/details/107822595