接口测试 requests的基本用法

requests的官方文档:http://cn.python-requests.org/zh_CN/latest/

requests是一个处理http请求的第三方库,所以,要了解requests的用法,需要先了解http协议,了解http协议的方法请出门右转。
看一下requests支持的web特性,根据运用过程中的需要去查看requests的官方文档或者搜索吧。

requests支持的web特性

  • Keep-Alive & 连接池

  • 国际化域名和 URL

  • 带持久 Cookie 的会话

  • 浏览器式的 SSL 认证

  • 自动内容解码

  • 基本/摘要式的身份认证

  • 优雅的 key/value Cookie

  • 自动解压

  • Unicode 响应体

  • HTTP(S) 代理支持

  • 文件分块上传

  • 流下载

  • 连接超时

  • 分块请求

  • 支持 .netrc

requests发送请求

使用requests发送网络请求非常简单,发送请求方式与HTTP类型相关。
示例接口地址:https://developer.github.com/v3/ http://httpbin.org/


GET请求
1、不传递参数的get请求
import requests

r = requests.get('http://httpbin.org/get')
print(r.status_code)

2、传递参数的get请求
import requests

payload = {'key1': 'hello', 'key2': 'world'}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
print(r.text)



POST请求

    post向服务器提交数据有4中常见的方式:

1 application/x-www-form-urlencoded

2 multipart/form-data

3 application/json

4 text/xml



提交数据的方式在headers的Content-Type中进行设定。

1、提交json格式的数据
import requests

headers = {"Content-Type": "application/json"}

payload = {'key1': 'hello', 'key2': 'world'}

r = requests.post('http://httpbin.org/post',
   data=payload, headers=headers)
   
print(r.url)

print(r.text)

image.png

2、POST上传文件
import requests

files = {'file': open('interface_url.xlsx', 'rb')}
r = requests.post('http://httpbin.org/post', files=files)
print(r.text)


PUT\DELETE\PATCH请求

请求格式与post一样。

requests中请求的响应类型

  • r.text:响应内容的格式与r.encoding的编码有关

  • r.content:二进制响应内容

  • r.json():json格式的响应内容

  • r.raw:原始响应内容,需要在发送请求时,设置stream=True

import requests

username = 'catleer'url = 'https://api.github.com'path = '/users/' + username

r = requests.get(url+path, stream=True)
print(r.url)
print(r.status_code)
print(r.encoding)
print("响应内容:", r.text)
print("二进制响应内容:", r.content)
print("json格式的响应内容:", r.json())
print("原始响应内容:", r.raw)
print(r.raw.read(100))with open("11.txt", 'wb') as fd:
    c = 1
    for chunk in r.iter_content(100):
        fd.write(chunk)
        c = c + 1
    print(c)
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值