python中http的一些编码转换

http的数据需要2种编码解码。

1. url中的特殊字符转换, 比如”,‘, :,//等

python3中通过urllib.parse.quote(..)和urllib.parse.unquote(..)来编码解码。

如:
import urllib.parse

url = "http://blog.csdn.net/muzizongheng"
en = urllib.parse.quote(url)
print(en)

de = urllib.parse.unquote(en)
print(de)

en = "http%3A%2F%2Fblog.csdn.net%2Fmuzizongheng"
de = urllib.parse.unquote(en)
print(de)

输出:
http%3A//blog.csdn.net/muzizongheng
http://blog.csdn.net/muzizongheng
http://blog.csdn.net/muzizongheng


2. http的一些Key&Value的组装

python3中通过urllib.parse.urlencode(..)来编码

如:
import urllib.parse

data = {
     'key1':"value1",
     'key2':"value2"
}
print(urllib.parse.urlencode(data))

输出:
key1=value1&key2=value2

原文地址:https://www.cnblogs.com/muzizongheng/p/3198303.html