Python使用Request发送POST请求

HTTP协议规定POST请求的数据必须放在消息主体中,但是并没有规定编码方式,因此可以使用多种方式对其进行编码。

服务器端通过请求头的中Content-Type字段来获知请求的消息主体以何种方式编码。具体的编码方式包括:

  1. application/x-www-form-urlencoded
  2. application/json
  3. multipart/form-data

示例代码:

import requests
import json

def requests_form():
    url = 'http://httpbin.org/post'
    data = {'k1':'v1', 'k2':'v2'}
    response = requests.post(url, data)
    return response

def requests_json():
    url = 'http://httpbin.org/post'
    data = s = json.dumps({'k1': 'v1', 'k2': 'v2'})
    response = requests.post(url, data)
    return response

def requests_multipart():
    url = 'http://httpbin.org/post'
    files = {'file': open('requests.txt', 'rb')}  # requests.txt中包含一句“Hey requests”
    response = requests.post(url, files=files)
    return response


if __name__ == "__main__":
    response1 = requests_form()
    response2 = requests_json()
    response3 = requests_multipart()
    
    print("From形式提交POST请求:")
    print(response1.text)
    print("Json形式提交POST请求:")
    print(response2.text)
    print("Multipart形式提交POST请求:")
    print(response3.text)