http的POST请求的编码有3种常用格式,具体如下:

  • application/x-www-form-urlencoded 最常见的post提交数据的方式,以form表单形式提交数据
  • application/json 以json格式提交数据
  • multipart/form-data 一般使用来上传文件(较少用)

一、urlencoded 编码

这里使用httbin.org公共测试接口,代码如下:

 1#!/usr/bin/env python
 2# coding=utf8
 3# Copyright (C)  www.361way.com site All rights reserved.
 4import requests,json
 5url = 'http://httpbin.org/post'
 6data = {'key1':'value1','key2':'value2'}
 7r =requests.post(url,data)
 8print(r)
 9print(r.text)
10print(r.content)

r.text返回的结果如下:

 1{
 2  "args": {},
 3  "data": "",
 4  "files": {},
 5  "form": {
 6    "key1": "value1",
 7    "key2": "value2"
 8  },
 9  "headers": {
10    "Accept": "*/*",
11    "Accept-Encoding": "gzip, deflate",
12    "Content-Length": "23",
13    "Content-Type": "application/x-www-form-urlencoded",
14    "Host": "httpbin.org",
15    "User-Agent": "python-requests/2.18.4"
16  },
17  "json": null,
18  "origin": "47.99.240.20, 47.99.240.20",
19  "url": "https://httpbin.org/post"
20}

这里post的结果其实相当于curl ‘http://httpbin.org/post’ -d ‘key1=value1&key2=value2’ 。

二、post json请求

以json格式发送post请求代码如下:

1import requests,json
2url_json = 'http://httpbin.org/post'
3data_json = json.dumps({'key1':'value1','key2':'value2'})   #dumps:将python对象解码为json数据
4r_json = requests.post(url_json,data_json)
5print(r_json)
6print(r_json.text)
7print(r_json.content)

r.text返回结果如下:

 1{
 2  "args": {},
 3  "data": "{\"key2\": \"value2\", \"key1\": \"value1\"}",
 4  "files": {},
 5  "form": {},
 6  "headers": {
 7    "Accept": "*/*",
 8    "Accept-Encoding": "gzip, deflate",
 9    "Content-Length": "36",
10    "Host": "httpbin.org",
11    "User-Agent": "python-requests/2.18.4"
12  },
13  "json": {
14    "key1": "value1",
15    "key2": "value2"
16  },
17  "origin": "47.99.240.20, 47.99.240.20",
18  "url": "https://httpbin.org/post"
19}

三、multipart请求

Requests以multipart形式发送post请求,具体代码实现如下所示:

1import requests,json
2url_mul = 'http://httpbin.org/post'
3files = {'file':open('E://report.txt','rb')}
4r = requests.post(url_mul,files=files)
5print(r)
6print(r.text)
7print(r.content)

执行r.text结果如下:

 1{
 2  "args": {},
 3  "data": "",
 4  "files": {
 5    "file": "{'key1':'value1','key2':'value2'}\n"
 6  },
 7  "form": {},
 8  "headers": {
 9    "Accept": "*/*",
10    "Accept-Encoding": "gzip, deflate",
11    "Content-Length": "178",
12    "Content-Type": "multipart/form-data; boundary=8462f97a62bb4d1fa863db2318196d28",
13    "Host": "httpbin.org",
14    "User-Agent": "python-requests/2.18.4"
15  },
16  "json": null,
17  "origin": "47.99.240.20, 47.99.240.20",
18  "url": "https://httpbin.org/post"
19}