requtsts模块

requtsts模块,上传文件

  files = {'files':open('test.xlsx','rb')}
  res = requtsts.post(url,files=files)

重定向

  resq = requtsts.get('http://httpbin.org/post',allow_redirects=False)
  resq.status_code

禁止证书验证

  resq = requtsts.get('http://httpbin.org/post',verify=False)

设置超时

  resq = requtsts.get('http://httpbin.org/post',timeout=10)
  如果超出设定的时间,或报timeoutError

"""
1、url
查询参数
2、请求方法
3、请求头
4、请求体
booy里的参数
"""

各种请求方法对应方法

  requests.get()
  requests.post()
  requests.put()
  requests.head()
  requests.options()

response = requests.get("https://www.baidu.com")

获取状态码

  print(response.status_code)

获取响应数据

  #content是原始的二进制数据
  print(response.content)

test属性是文本格式
encoding属性可以获取和设置字符编码

  response.encoding = 'utf-8'
  print(response.text)

获取响应headers属性

  print(response.headers)

响应url

  print(response.url)

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。
常见的form表单可以直接使用data参数进行报文提交,而data的对象则是python中的字典类型。
用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为'{"a": 1, "b": 2}'的这种形式。
不管json是str还是dict,如果不指定headers中的content-type,默认为application/json,data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单,data为str时,如果不指定content-type,默认为text/plain,所以传入参数的类型接口指定为json时,需要加引号,json为dict时,如果不指定content-type,默认为application/json,json为str时,如果不指定content-type,默认为application/json

案例

import json
from Api.test_headers_toten import odoo_toten,yjkd_toten
import requests


class getapi():
    def __init__(self, url,params=None, headers=None, data=None):
        self.url = url
        self.params = params
        self.headers = headers
        self.data = data


    def get(self):
        set_get = requests.get(url=self.url, params=self.params, headers=self.headers)
        return set_get

    def post(self):
        set_post = requests.post(url=self.url, headers=self.headers, json=self.data)
        return set_post
posted @ 2020-11-27 16:14  Old_Arthurㄟ  阅读(133)  评论(0编辑  收藏  举报