HTTP :超文本传输协议(HyperText Transfer Protocol)
请求报文包含三部分:
a、请求行:包含请求方法、URl、HTTP版本信息
b、请求头部(headers)字段
c、空行
d、请求内容实体(body)
响应报文包含三部分:
a、状态行:包含HTTP版本、状态码、状态码的原因短语
b、响应头部(headers)字段
c、响应内容(body)实体
请求:
(1)请求方法 :get方法、post方法、put方法、delete方法
(2)请求地址 :就是浏览器地址栏里输入的那个地址
(3)请求头: 主要看Centent-Type这个字段
(4)请求体 : 主要有两种格式 ,JSON和表单 ,它们的编码方式不同 。
响应:
(1)状态码 :200,302,400,404,500
(2)响应体 :接口返回的结果就在这里面 ,一般都是json格式。
1.get方法
"""
get(url,headers) : 实现http协议中的get请求 。
"""
# 1. 导包
import requests
# 2. 请求
res = requests.get("http://www.baidu.com")
# 3. 查看响应结果
print(res.text)
2.post方法-表单请求
"""
"""
# 1. 导包
import requests
# 2. 请求接口
login_url = "http://localhost/?"
login_data = {"username":"x","password":"123456"}
res = requests.post(login_url,data=login_data)
# 3. 查看结果
print(res.text)
3.post方法-JSON格式
"""
"""
# 1. 导包
import requests
# 2. 请求接口
login_url = "http://localhost:8080/"
login_data = {"username":"x","password":"123456"}
res = requests.post(login_url,json=login_data)
# 3. 查看结果
print(res.text)
4.属性介绍
"""
"""
# 查看响应内容
# 1. 导包
import requests
# 2. 请求百度
response = requests.get("http://www.baidu.com")
print(response)
response.encoding = 'utf-8'
# 3 输出主要信息
print("查看响应状态码:",response.status_code)
print("查看请求地址url:",response.url)
print("查看响应的字符编码:",response.encoding)
print("查看响应头地址:",response.headers)
print("查看响应体的文本信息:",response.text)
5.json()方法
"""
"""
import requests
response = requests.get("http://www.x")
response.encoding = 'utf-8'
result = response.json()
print(result)
# 获取
result = result.get('x')
print(result)
- method : 传递请求方法,比如get、post、delete、put等
- url : 传递url
- params : 传递查询参数
- data : 传递请求体数据
- headers :传递请求头数据
- cookies : 传递cookies数据
- files:支持上传文件
- json :传递请求体数据