python post请求实例 & json -- str互相转化(application/x-www-form-urlencoded \ multipart/form-data)

目录:

urlencode & quote & unquote (url 中带中文参数)

python httplib urllib urllib2区别(一撇)

python post请求实例 & json -- str互相转化(application/x-www-form-urlencoded \ multipart/form-data)


第一部分:HTTP 协议规定POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。常见的四种编码方式如下:1)application/x-www-form-urlencoded 2)multipart/form-data   3)application/json   4)text/xml   详细如下:

1application/x-www-form-urlencoded 
这应该是最常见的 POST提交数据的方式了。浏览器的原生 form表单,如果不设置 enctype属性,那么最终就会以 application/x-www-form-urlencoded方式提交数据。请求类似于下面这样(无关的请求头在本文中都省略掉了):

POST http://www.example.com HTTP/1.1    Content-Type:

application/x-www-form-urlencoded;charset=utf-8

title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3

2multipart/form-data 
这又是一个常见的 POST数据提交的方式。我们使用表单上传文件时,必须让 form enctyped 等于这个值,下面是示例

POST http://www.example.com HTTP/1.1

Content-Type:multipart/form-data;boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="text"

title

------WebKitFormBoundaryrGKCBY7qhFd3TrwA

Content-Disposition: form-data; name="file"; filename="chrome.png"

Content-Type: image/png

PNG ... content ofchrome.png...

------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

3application/json (下面会详细讲解json –json_str的互相转化)
application/json 
这个 Content-Type作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON字符串。由于 JSON规范的流行,除了低版本 IE之外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON的函数,使用 JSON不会遇上什么麻烦。

4text/xml 
它是一种使用 HTTP作为传输协议,XML 作为编码方式的远程调用规范。

那么Python在调用外部http请求时,post请求怎么传请求体呢?说实话楼主只实践过1application/x-www-form-urlencoded】【2multipart/form-data】和【3application/json 


一、application/x-www-form-urlencoded

import urllib

url = "http://www.example.com"

body_value = {"package":"com.tencent.lian","version_code":"66" }

body_value = urllib.urlencode(body_value)

request = urllib2.Request(url, body_value)

request.add_header(keys, headers[keys])

result = urllib2.urlopen(request ).read()

二、multipart/form-data 
需要利用pythonposter模块,安装posterpip install poster 
代码:

from poster.encode import multipart_encode

from poster.streaminghttp importregister_openers

 

url = "http://www.example.com"

body_value = {"package":"com.tencent.lian","version_code":"66" }

register_openers()

datagen, re_headers =multipart_encode(body_value)

request = urllib2.Request(url, datagen,re_headers)

如果有请求头数据,则添加请求头

request .add_header(keys, headers[keys])

result = urllib2.urlopen(request ).read()

三、application/json

import json

 

url = "http://www.example.com"

body_value = {"package":"com.tencent.lian","version_code":"66" }

register_openers()

body_value = json.JSONEncoder().encode(body_value)

request = urllib2.Request(url, body_value)

request .add_header(keys, headers[keys])

result = urllib2.urlopen(request ).read()

参看自  Python请求外部POST请求,常见四种请求体

第二部分:json 与 str的相互转化,json.dumps() --> encoding / json.loads() --> decoding 仅仅支持简单数据类型(stringunicodeintfloatlisttupledict); 自定义的类或数据类型需要借助于

在Python标准库的json包中,提供了JSONEncoder和JSONDecoder两个类来实现Json字符串和dict类型数据的互相转换。

概念

序列化(Serialization:将对象的状态信息转换为可以存储或可以通过网络传输的过程,传输的格式可以是JSONXML等。反序列化就是从存储区域(JSONXML)读取反序列化对象的状态,重新创建该对象。

JSONJavaScript Object Notation:一种轻量级数据交换格式,相对于XML而言更简单,也易于阅读和编写,机器也方便解析和生成,JsonJavaScript中的一个子集。

Python2.6开始加入了JSON模块,无需另外下载,PythonJson模块序列化与反序列化的过程分别是 encoding decoding

encoding:把一个Python对象编码转换成Json字符串
decoding
:把Json格式字符串解码转换成Python对象
对于简单数据类型(stringunicodeintfloatlisttupledict),可以直接处理。

json.dumps方法对简单数据类型encoding:
import json
data = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象
print "DATA:",repr(data)
 
data_string = json.dumps(data)
print "JSON:",data_string

输出:

DATA: [{'a':'A','c':3.0,'b':(2,4)}] #pythondict类型的数据是没有顺序存储的
JSON: [{"a":"A","c":3.0,"b":[2,4]}]  

JSON的输出结果与DATA很相似,除了一些微妙的变化,如python的元组类型变成了Json的数组,PythonJson的编码转换规则是: 

json.loads方法处理简单数据类型的decoding(解码)转换
import json
data = [{'a':"A",'b':(2,4),'c':3.0}]  #list对象
 
data_string = json.dumps(data)
print "ENCODED:",data_string
 
decoded = json.loads(data_string)
print "DECODED:",decoded
 
print "ORIGINAL:",type(data[0]['b'])
print "DECODED:",type(decoded[0]['b'])

输出:

ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}]
DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}]
ORIGINAL: <type 'tuple'>
DECODED: <type 'list'>

Python标准库的json包中,提供了JSONEncoder和JSONDecoder两个类来实现Json字符串和dict类型数据的互相转换。

1.  #!/usr/bin/python3  

2. from json import *  

3.  if __name__=="__main__":     

4.    d={}  

5.     d['a'] =1  

6.    d['b']=2  

7.     d[3]='c'  

8.    d[4]=['k','k1']    

9.     #Python dict类型转换成标准Json字符串  

10.   k=JSONEncoder().encode(d)  

11.    print(type(k))  

12.   print(k)  

13.    #json字符串转换成Python dict类型  

14.   json_str='{"a":1,"b":2,"3":"c","4":["k","k1"]}'  

15.    d=JSONDecoder().decode(json_str)  

16.   print(type(d))  

17.    print(d)  

18.  

运行截图:

需要注意的是:标准Json字符串必须使用双引号(")而不能使用单引号('),否则从字符串转换成dict类型会提示出错。



转载自:https://blog.csdn.net/u010700335/article/details/72902640

猜你喜欢

转载自blog.csdn.net/changkai456/article/details/80765085
今日推荐