zoukankan      html  css  js  c++  java
  • Requests接口测试(三)

    一、定制请求头

    我们先来看一下,关于请求头的定制演示,相信了解http协议的小伙伴应该对请求头部headers请求头部并不陌生,那么作为实际工作中的我们,如果想自定义一些请求头的信息,我们应该怎么办呢?其实很简单,只需要将发送的自定义请求里面传入一个dict(字典即可),下面我们来看一下代码示例:

    注: 所有的header值必须是string、bytestringunicode,虽然传递unicode header是允许的,但不建议这样做!

    二、定制请求头代码示例

    #coding=utf-8
    
    import requests
    
    if __name__ == '__main__':
        print ('开始演示------>')
        url = 'http://www.baidu.com'
        #定义请求头数据
        headers={'user-agent':'www.testingunion.com',
                 'custom-head':'fighter_test'}
        #发送自定义请求头数据
        r = requests.get(url,headers=headers)
        

    我们运行上面的代码前,需要先打开fidder,然后运行上面的代码,在fidder中可以查询设置的请求头信息是否成功,如下图:

    三、Post请求示例

    我们看一下post是如何发送json数据到服务器的:

    import requests
    
    if __name__ == '__main__':
        print ('开始演示------>')
        #目标地址
        url = 'http://jsonplaceholder.typicode.com/posts'
        #自定义头
        headers={
            'custom-post':'my-post',
            'custom-header':'my-json-header'
        }
        #要post的数据
        json_data = {'title':'deeptest',
                     'body':'fighter007',
                     'userId':'1'}
        #post json格式的数据
        r = requests.post(url,json=json_data,headers=headers)
        #打印返回结果
        print(r.text)

    返回结果:

    使用fidder抓包分析数据结果:

    到此我们就演示完了,是不是很简单呢?

  • 相关阅读:
    mysql practice
    image update to ubuntu18.04
    C++11 new feature
    bazel remote executor--- buildfarm( in docker)
    python3学习笔记13(数据结构)
    python3学习笔记12(变量作用域)
    python3学习笔记11(函数)
    jmeter 01 之beanshell preprocessor
    python3学习笔记10(迭代器和生成器)
    python3学习笔记十(循环语句)
  • 原文地址:https://www.cnblogs.com/fighter007/p/8453723.html
Copyright © 2011-2022 走看看