zoukankan      html  css  js  c++  java
  • 【模块】:Requests(二)

    Requests模块常见的4中post请求

    HTTP 协议规定 POST 提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。常见的四种编码方式如下: 

    1、application/x-www-form-urlencoded 

    这应该是最常见的 POST 提交数据的方式了。浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。请求类似于下面这样:

    import requests
    import json
    
    CONFIG = {
        'url': 'http://192.168.90.10:8888/',
        'headers': {'Content-Type': 'application/x-www-form-urlencoded'}
    }
    data = {'content': 'hello',
            'digital': '0',
            'punctuate': '1',
            'engModel': '2'}
    
    url = CONFIG['url']
    headers = CONFIG['headers']
    
    response = requests.post(url=url, data=data,headers=headers,timeout=1)
    print(response.content)

    用wirshark进行抓包,分析请求的数据格式

    追踪http数据流,可以看到请求的数据进行了这样的拼接content=hello&engModel=2&punctuate=1&digital=0

    2、multipart/form-data 

    这又是一个常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctyped 等于这个值,下面是示例

    import requests
    import json
    
    CONFIG = {
        'url': 'http://192.168.90.10:8888/',
        'headers': {'Content-Type': 'multipart/form-data'}
    }
    data = {'content': 'hello',
            'digital': '0',
            'punctuate': '1',
            'engModel': '2'}
    
    url = CONFIG['url']
    headers = CONFIG['headers']
    
    response = requests.post(url=url, files=data,headers=headers,timeout=1)
    print(response.content)
    

    用wirshark进行抓包,分析请求的数据格式

    追踪http数据流,可以看到请求的数据

    3、application/json 

    application/json 这个 Content-Type 作为响应头大家肯定不陌生。实际上,现在越来越多的人把它作为请求头,用来告诉服务端消息主体是序列化后的 JSON 字符串。由于 JSON 规范的流行,除了低版本 IE 之外的各大浏览器都原生支持 JSON.stringify,服务端语言也都有处理 JSON 的函数,使用 JSON 不会遇上什么麻烦。

    import requests
    import json
    
    CONFIG = {
        'url': 'http://192.168.90.10:8888/',
        'headers': {'Content-Type': 'application/json'}
    }
    data = {'content': 'hello',
            'digital': '0',
            'punctuate': '1',
            'engModel': '2'}
    
    url = CONFIG['url']
    headers = CONFIG['headers']
    
    response = requests.post(url=url, data=json.dumps(data),headers=headers,timeout=1)
    print(response.content)

    用wirshark进行抓包,分析请求的数据格式

    追踪http数据流,可以看到请求的数据

     

    4、text/xml 

    它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。

  • 相关阅读:
    HTML中使用Vue+Dhtmlxgantt制作任务进度图
    Vue中使用js-xlsx导出Data数据到Excel
    Vue生命周期
    ajax调用免费的天气API
    maven无法自动下载依赖包settings.xml文件配置
    idea打开项目没有src目录
    java jdk idea maven安装及配置
    CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://conda.anaconda.org/pytorch
    The procedure entry point OPENSSL_sk_new_reserve could not be located in the dynamic link library
    Nuget打包没有注释显示
  • 原文地址:https://www.cnblogs.com/lianzhilei/p/8609421.html
Copyright © 2011-2022 走看看