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 作为编码方式的远程调用规范。

  • 相关阅读:
    Bootstrap 2.2.2 的新特性
    Apache POI 3.9 发布,性能显著提升
    SQL Relay 0.48 发布,数据库中继器
    ProjectForge 4.2.0 发布,项目管理系统
    红帽企业 Linux 发布 6.4 Beta 版本
    红薯 快速的 MySQL 本地和远程密码破解
    MariaDB 宣布成立基金会
    Percona XtraBackup 2.0.4 发布
    Rocks 6.1 发布,光盘机群解决方案
    精通Servlet研究,HttpServlet的实现追究
  • 原文地址:https://www.cnblogs.com/lianzhilei/p/8609421.html
Copyright © 2011-2022 走看看