zoukankan      html  css  js  c++  java
  • 随笔:Python+requests进行post请求之常见的三种入参

    随笔:Python+requests进行post请求之常见的三种入参

    1、json格式入参,此处入参是汉字

    #coding=utf-8
    import requests
    url = '请求地址'
    header = {'content-type':'application/json'}
    t = "心灵"
    data = {"text":t}
    
    #这里需要注意data和json的区别
    response = requests.post(url=url,headers=header,json=data)
    #对请求结果进行编码转换,转换成汉字
    request = response.text.encode('utf-8').decode('unicode_escape')
    #不转换返回的结果
    print(response.text)
    #转换后返回的结果
    print(request)
    

    返回结果:

    {"value":{"2516"}}
    
    {"value":{"情感。"}}
    
    
    Process finished with exit code 0
    

    2、csv,txt等文件格式入参

    import requests
    from requests_toolbelt.multipart.encoder import MultipartEncoder
    
    filename = r'D:	estcloudAImxfileOLT_DEMO.csv'
    file = open(filename,'rb')
    url = '请求地址'
    data = MultipartEncoder(
        fields={
            'OLT_INFO':
                ('OLT_DEMO.csv',
                 file,
                 'application/octet-stream')
        }
    )
    header={}
    header['content-type'] = data.content_type
    response = requests.post(url=url,headers=header,data=data)
    print(response.text)
    

    3、图片格式进行base64编码加密入参

    import requests
    import base64
    
    
    photo = r'D:	estcloudAIphototestwjj.jpg'
    #fp = open(photo,'rb')
    
    
    with open(photo,'rb') as f:
        base64_data = base64.b64encode(f.read())
        s = base64_data.decode()
    
    
    url = '请求url'
    data = '{"imageBase64":"'+s+'"}'
    header = {'Content-Type': 'application/json'}
    response = requests.post(url=url,headers=header,data=data)
    
    print(response.text)
    

    番外:
    还有常见的get请求也大同小异

  • 相关阅读:
    统计内存使用情况
    自动化测试---PO设计模式
    初识xshell
    pip插件遇到问题(fetch URL https)
    为什么大家都热衷于挖矿呢?
    80个python练习以及python一些值得收藏的教程或博客
    面试问到一个,让你写一下朋友圈点赞功能的测试用例!记录一下
    ajax异步请求302
    Java学习
    MVC 带扩展名的路由无法访问
  • 原文地址:https://www.cnblogs.com/caodingzheng/p/14007083.html
Copyright © 2011-2022 走看看