python requests 应用

1. GET 请求

  • Content-Type: application/json;charset=utf-8
import requests

url = "http://xxxx"
body = {"name": "zhangsan"}
headers = {"Content-Type": "application/json;charset=utf-8"}

# params 字典类型自动转url编码
response = requests.get(url = url, params=body, headers = headers)

# 以unicode格式返回响应的内容
print(response.text)

# 返回响应码
print(response.status_code)

# 返回字典数据
print(response.json())

2. POST 请求

  • json.dumps()函数是将字典转化为字符串
  • json.loads()函数是将字符串转化为字典
response = requests.post(url = url, data = json.dumps(body), headers = headers)

3. url 转码,POST 请求

  • Content-Type: application/x-www-form-urlencoded;charset=utf-8
from urllib import parse

headers["content_type"] = "application/x-www-form-urlencoded;charset=utf-8"

response = requests.post(url=url, data = parse.urlencode(body), headers=headers)
posted @ 2021-09-14 18:13  tt_贝塔  阅读(38)  评论(0编辑  收藏  举报