python HTTP 请求和 base64 编码 json

python 发送 HTTP 请求
import requests
url='http://url/api'
s=({"hello":"world","name":"zhenng"})
r=requests.post(url,data=s)
jf= json.dumps(r.json(), sort_keys=True, indent=4, separators=(',', ':'))
print(jf)
print(r.status_code)
requests.post 发送 HTTP 中的 POST 请求,其中可以以 data 方式发送 form 表单格式的数据,也可以以 json 方式发送 json 格式的数据,注意服务端是用何种方式解析的,不然会获取不到数据。
json.dumps 将 python 中的 json 对象转换为字符串并格式化
r.status_code 返回请求的状态码
python base64 编码 json
import base64
import json
if __name__=="__main__":
js={"hello":"world","name":"zhenng"}
json_str=json.dumps(js)
base64_str=base64.b64encode(json_str.encode('utf-8')).decode('utf8')
print(base64_str)
print(base64.b64encode(json_str.encode('utf-8')))
print (type(js))
print(type(json_str))
print(type(json_str.encode('utf-8')))
print(type(base64.b64encode(json_str.encode('utf-8'))))
# eyJoZWxsbyI6ICJ3b3JsZCIsICJuYW1lIjogInpoZW5uZyJ9
# b'eyJoZWxsbyI6ICJ3b3JsZCIsICJuYW1lIjogInpoZW5uZyJ9'
# <class 'dict'>
# <class 'str'>
# <class 'bytes'>
# <class 'bytes'>
# <class 'str'>
json.dumps 将 python 中 json 对象转换为 json 字符串
encode('utf-8') 将 json 字符串转换为二进制,b64encode() 需要二进制参数
b64encode() 返回 base64 编码后的二进制字符串,decode('utf8') 将二进制字符串又转换为 utf-8 字符串
base64 编码指的是将所有的二进制字符串都通过64个字符来标识,转化成了一个 base64 字符串,base64 解码是将 base64 字符串转换为二进制编码字符串。
base64 字符串还是一个二进制字符串,只不过是只用64个字符表示更符合人的直觉。
utf8 编码是将 python 字符串编码为二进制字符串,解码是将二进制字符串转换为 python 字符串。
未经 utf8 编码的 base64 字符串是一个二进制字符串,带有一个 b 标识,因为 base64 编码中的 64 个字符都能用 utf8 标识,因此未经 utf8 编码的字符串和经过utf8 编码的字符串仅仅是格式不同,字符串是相同的。




