• 【模块】: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 作为编码方式的远程调用规范。

  • 相关阅读:
    luogu1525 [NOIp2011]关押罪犯 (并查集)
    luogu1084 [NOIp2012]疫情控制 (二分答案+倍增+dfs序)
    luogu1083 [NOIp2012]借教室 (二分答案+差分)
    bzoj4152 The Captain (dijkstra)
    luogu1081 [NOIp2012]开车旅行 (STL::multiset+倍增)
    suoi22 WRX知识树(dfs序)
    [HNOI2010]弹飞绵羊
    1596: [Usaco2008 Jan]电话网络
    [Tyvj Jan]青蛙跳荷叶
    [BZOJ1116] CLO
  • 原文地址:https://www.cnblogs.com/lianzhilei/p/8609421.html
Copyright © 2020-2023  润新知