zoukankan      html  css  js  c++  java
  • requests---HTTPS请求

      做过接口测试的都会发现,现在的接口都是HTTPS协议了,今天就写一篇如何通过request发送https请求,如果不是很了解HTTP协议的同学可以看下我的另外一篇博客什么是HTTP

    什么是HTTPS

    HTTPS 的全称是Hyper Text Transfer Protocol over Secure Socket Layer ,是以安全为目标的HTTP通道,简单的讲是HTTP的安全版本,即HTTP下加入SSL层,简称HTTPS

    其中HTTPS的安全基础为SSL,因此通过它的传输的内容都是经过SSL加密的,它的主要作用可以分为两种:

    1、建立一个信息安全通道来保证数据传输的安全

    2、确保网站的真实性,凡是使用了HTTPS 的网站,都可以通过点击浏览器地址栏的锁头标志来查看网站认证之后的真实信息。

    requests发送HTTPS

    1.requests发送请求

    2.携带请求头发送https

    # coding:utf-8
    import requests
    # 请求地址
    url = "https://www.qlchat.com"
    headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chro'
                          'me/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400'
    }
    r = requests.get(url,headers=headers)
    print(r.status_code)
    
    代码结果:
    错误提示:requests.exceptions.SSLError: HTTPSConnectionPool(host='www.qlchat.com', port=443)

    发现请求后代码出现了报错,发现是SSL的问题。

    SSL证书验证

    requests中是有SSL证书认证的,SSL像默认浏览器一样,SSL 验证默认是开启的,如果证书验证失败,Requests 会抛出 SSLError,如果证书验证失败的时候加上verify=False

    源码:

    def request(method, url, **kwargs):
        """Constructs and sends a :class:`Request <Request>`.
        :type allow_redirects: bool
        :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
        :param verify: (optional) Either a boolean, in which case it controls whether we verify
                the server's TLS certificate, or a string, in which case it must be a path
                to a CA bundle to use. Defaults to ``True``.
    
    代码太多了,删除了一些

    回到上面的代码,加入verify=False再次请求,会发现请求成功,但是会报一行安全错误,

    # coding:utf-8
    import requests
    # 请求地址
    url = "https://www.qlchat.com"
    headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chro'
                          'me/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400'
    }
    r = requests.get(url,headers=headers,verify=False)
    print(r.status_code)

    解决上图报错。导入urllib3模块,引入urllib3.disable_warnings()方法

    再次请求就会发现报错没有了

    感觉对你有帮助,或者喜欢的小伙伴们,点个关注,持续更新,让我们在测试的道路上更加精彩 

  • 相关阅读:
    interview ms1 N_Dorm
    interview ms1 robert move **
    LeetCode OJ-- Jump Game II **
    LeetCode OJ-- Jump Game
    LeetCode OJ-- Palindrome Partitioning II ***
    LeetCode OJ--Palindrome Partitioning **
    LeetCode OJ--Palindrome Number
    LeetCode OJ-- Linked List Cycle II **
    3dContactPointAnnotationTool开发日志(十一)
    3dContactPointAnnotationTool开发日志(十)
  • 原文地址:https://www.cnblogs.com/qican/p/11176527.html
Copyright © 2011-2022 走看看