• 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抓包分析数据结果:

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

  • 相关阅读:
    linux 相关( 随时更新)
    django admin 修改批量操作内容
    区块链
    关于读取excel 和 写excel
    git基本用法
    服务器与本地的控制工具unison
    爬虫框架 Scrapy
    爬虫高性能 asyncio库 twisted库 tornado库
    爬虫请求库之selenium模块
    爬虫请求库
  • 原文地址:https://www.cnblogs.com/fighter007/p/8453723.html
Copyright © 2020-2023  润新知