Skip to main content

Command Palette

Search for a command to run...

python HTTP 请求和 base64 编码 json

Published
1 min read
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 编码的字符串仅仅是格式不同,字符串是相同的。

More from this blog

根据前、中、后序数组构造二叉树

根据两个遍历数组生成二叉树,主要是固定住一个根节点,然后去另一个数组查找下标,划分数组做左右子树,再递归执行左子树和右子树。 这里主要讨论的是使用切片的过程中如何确定切片的起始点,即切片的区间,利用的是左子树的长度。 前序和中序构造二叉树 105. 从前序与中序遍历序列构造二叉树 递归加切片, python 中可以使用 index 函数直接获取值的下标。 注意:切片是左闭右开区间,最后一个值取不到 切片的下标如何思考:利用左子树的长度来辅助思考。idx 是中序数组中的当前节点下标,所以左子...

Apr 3, 20242 min read
根据前、中、后序数组构造二叉树

二叉树的遍历

掌握两种方法进行二叉树的遍历,这里重点看迭代法是怎么写,迭代法使用栈来模拟递归中的栈,也可以使用一种通用方式进行前、中、后序遍历。 递归法 def dfs(root) { // 前序遍历 dfs(root.left) // 中序遍历 dfs(root.right) // 后序遍历 } 迭代法:迭代法是用 stack 栈来模拟递归栈 下面这种写法可以统一前序、中序、后序遍历方式的写法,只需要改变入栈顺序 前序遍历:中,左,右中序遍历:左,中,右后序遍历:左...

Apr 3, 20242 min read
二叉树的遍历

函数式编程在 Java 和 Go 中的应用

函数式编程是一种 "编程范式"(programming paradigm),就是如何编写程序的方法论。 函数式编程特点: 函数是"第一等公民" 只用"表达式",不用"语句" "表达式"(expression)是一个单纯的运算过程,总是有返回值;"语句"(statement)是执行某种操作,没有返回值。函数式编程要求,只使用表达式,不使用语句。也就是说,每一步都是单纯的运算,而且都有返回值。 没有"副作用" 所谓"副作用"(side effect),指的是函数内部与外部互动(最典型的情况,就...

Jun 26, 20237 min read
函数式编程在 Java 和 Go 中的应用

Untitled Publication

13 posts