pythonrequests模块发送post请求

Posted sysu_lluozh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pythonrequests模块发送post请求相关的知识,希望对你有一定的参考价值。

常见的Content-Type如下:

  1. application/x-www-form-urlencoded
    这是最常见的数据类型,通常表明请求的数据类型是键值对类型,页面form表单数据,如
    username=lluozh&password=123456

  2. application/json
    这意味着请求的数据类型是 Json 格式的数据:
    "username":"lluozh", "password":"123456"

  3. multipart/form-data
    multipart/form-data通常用于上传文件

  4. application/xml
    数据格式为xml格式

一、Form表单

浏览器的原生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

请求形式

r = requests.post(
			url='',
			data='key1':'value1','key2':'value2',
			headers='Content-Type':'application/x-www-form-urlencoded'
)
print(r.text)

输出:


  "args": , 
  "data": "", 
  "files": , 
  "form": 
    "key1": "value1", 
    "key2": "value2"
  , 
  "headers": 
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-61db8ec1-0df0ff7d0902ff8d6d16c924"
  , 
  "json": null, 
  "origin": "183.63.127.84", 
  "url": "http://httpbin.org/post"

可以看到,请求头中的Content-Type字段已设置为application/x-www-form-urlencoded,且d = 'key1': 'value1', 'key2': 'value2'以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据

二、json格式

对于提交json串,主要是用于发送ajax请求中,动态加载数据

2.1 data参数

  • 把data进行json编码
r = requests.post(
    url='http://lazytools.feidee.cn/v1/qrcode/log',
    data=json.dumps(d),
    headers='Content-Type':'application/json'
)
print(r.headers)
print(r.text)

输出


	'Server': 'Tengine',
	'Date': 'Tue, 11 Jan 2022 00:18:45 GMT',
	'Content-Type': 'application/json',
	'Transfer-Encoding': 'chunked',
	'Connection': 'keep-alive',
	'X-from': '3.195:9280'


"code":0,"data":null,"message":null
  • 直接使用data进行发送json格式
r = requests.post(
    url='http://lazytools.feidee.cn/v1/qrcode/log',
    data=d,
    headers='Content-Type':'application/json'
)
print(r.headers)
print(r.text)

输出


	'Server': 'Tengine',
	'Date': 'Tue, 11 Jan 2022 00:18:45 GMT',
	'Content-Type': 'application/json',
	'Transfer-Encoding': 'chunked',
	'Connection': 'keep-alive'


"code":-1,"data":null,"message":"请求参数解析失败"

即使写上'Content-Type':'application/json; charset=UTF-8',返回依然出错,原因就在于请求实体的格式错误,服务端无法解码

2.2 json参数

自动使用json方式发送,而且在请求头中也不用显示声明'Content-Type':'application/json; charset=UTF-8'

  • 发送json参数数据
import json
import requests
d = "category": 0,"content": "lluozh","source": 1
r = requests.post(
    url='http://lazytools.feidee.cn/v1/qrcode/log',
    json=d,
    headers='Content-Type':'application/json'
)
print(r.headers)
print(r.text)

输出


	'Server': 'Tengine',
	'Date': 'Tue, 11 Jan 2022 00:18:45 GMT',
	'Content-Type': 'application/json',
	'Transfer-Encoding': 'chunked',
	'Connection': 'keep-alive',
	'X-from': '3.195:9280'


"code":0,"data":null,"message":null
  • 无需显示声明Content-Type
r = requests.post(
    url='http://lazytools.feidee.cn/v1/qrcode/log',
    json=d
)
print(r.headers)
print(r.text)

输出


	'Server': 'Tengine',
	'Date': 'Tue, 11 Jan 2022 00:18:45 GMT',
	'Content-Type': 'application/json',
	'Transfer-Encoding': 'chunked',
	'Connection': 'keep-alive',
	'X-from': '3.196:9280'


"code":0,"data":null,"message":null

三、form-data

除了传统的application/x-www-form-urlencoded表单,另一个经常用到的是上传文件用的表单,这种表单的类型为multipart/form-data

multipart/form-data有两种格式发送

3.1 encode_multipart_formdata

d = 
		'field0': 'value',
		'field1': 'value',
        'field2': ('file', '/Users/lluozh/导入模板 .xlsx')

for key,value in d.items():
    if isinstance(value,tuple) and value[0] == 'file':
        # 文件路径
        file_path = value[1]
        if file_path is not None:
            d[key] = (os.path.basename(file_path), open(file_path, 'rb').read())
encode_data = encode_multipart_formdata(d)
header['Content-Type'] = encode_data[1]
d = encode_data[0]
r = requests.post(
		url='http://httpbin.org/post', 
		headers=header,
		data=d
)
print(r.headers)
print(r.text)

输出


	'Server': 'openresty',
	'Date': 'Tue, 11 Jan 2022 02:49:48 GMT',
	'Content-Type': 'application/json;charset=UTF-8',
	'Transfer-Encoding': 'chunked',
	'Connection': 'keep-alive',
	'X-APM-TraceId': '2fba0ac589e4933da992c642ac5e54b8'


"statusCode":200,"message":"SUCCESS","data":

3.2 binary

上传文件也可以通过binary的方式上传
Content-Type类型为multipart/form-data,以multipart形式发送post请求,只需将文件传给 requests.post()的files参数即可

import requests

url = 'http://httpbin.org/post'
files = 'file': open('/Users/lluozh/upload.txt', 'rb')
r = requests.post(url, files=files)  # 文件传给requests.post()的files参数

print(r.text)

输出


  "args": , 
  "data": "", 
  "files": 
    "file": "Hello world"
  , 
  "form": , 
  "headers": 
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "157", 
    "Content-Type": "multipart/form-data; boundary=a54ce101a1fedbc5409cd63be316e15e", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-61dcf3f4-46bbf6355ec28c9d6c852f80"
  , 
  "json": null, 
  "origin": "183.63.127.84", 
  "url": "http://httpbin.org/post"

文本文件report.txt的内容只有一行:Hello world!,从请求的响应结果可以看到数据已上传到服务端中

四、xml

支持raw的格式发送数据

  • 请求正文是xml
import requests


r = requests.post(
	url='http://httpbin.org/post',
	data='<?xml  ?>',
	headers='Content-Type':'text/xml'
)
print(r.text)

输出


  "args": , 
  "data": "<?xml  ?>", 
  "files": , 
  "form": , 
  "headers": 
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "9", 
    "Content-Type": "text/xml", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-61dcf634-08a023146a0bc8af62251a10"
  , 
  "json": null, 
  "origin": "183.63.127.84", 
  "url": "http://httpbin.org/post"

  • 支持json字符串的格式
r = requests.post(
	url='http://httpbin.org/post',
	data=json.dumps('key1':'value1','key2':'value2'),
	headers='Content-Type':'text/xml'
)
print(r.text)

输出


  "args": , 
  "data": "\\"key1\\": \\"value1\\", \\"key2\\": \\"value2\\"", 
  "files": , 
  "form": , 
  "headers": 
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "36", 
    "Content-Type": "text/xml", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0", 
    "X-Amzn-Trace-Id": "Root=1-61dcf634-0274a69143501a590e8925fa"
  , 
  "json": 
    "key1": "value1", 
    "key2": "value2"
  , 
  "origin": "183.63.127.84", 
  "url": "http://httpbin.org/post"


以上是关于pythonrequests模块发送post请求的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法使用 Python Requests 库确认 POST 请求是不是实际上是通过代理发送的?

pythonrequests模块post参数data和json的区别

请求中的数据和参数有啥区别?

大概看了一天python request源码。写下python requests库发送 get,post请求大概过程。

Python接口测试-使用requests模块发送post请求

python之使用request模块发送post和get请求