zoukankan      html  css  js  c++  java
  • Python接口自动化基础---post请求

    常见的post传递参数的类型有以下两种:

    第一种:application/x-www-form-urlencoded,浏览器原生的form表单,格式如下:input1=xxx&input2=ooo

    第二种:application/json ,这是常见的json格式,格式如下:{"input1":"xxx","input2":"ooo","remember":false}

    1、以表单形式传递参数

    只需简单的传递一个字典给data关键字,在发送请求的时候,会自动编码为表单的形式

    param1={'username':'test','password':'123456'}
    r1=requests.post('http://host/login',data=param1)
    print(r1.text)
    print(r1.status_code)
    
    
    结果:
    {"id":413,"username":"test","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QiLCJpZCI6NDEzLCJpYXQiOjE1MDczODI1MDYsImV4cCI6MTU5Mzc4MjUwNn0.Qdexnx_x4_Vm5Mw7fPgKCUoKto4ujtLc9NTtk7hxOsE"}
    200

    2、以json格式传递参数:

    想要在post请求中使用data关键字来传递json格式的字符串,首先得把dict转为string

    import requests
    import json
    
    url='http://www.tuling123.com/openapi/api'
    
    data={'key':'4b6ce82fbe554a11b99dabfa3a4ae6d9','info':'我的城市在北京,请你记住','userid':'jxn'}
    print(type(data))
    json_data=json.dumps(data)
    print(type(json_data))
    
    r=requests.post(url,data=json_data)
    print(r.text)
    print(type(r.text))
    
    结果:
    <class 'dict'>
    <class 'str'>
    {"code":100000,"text":"你不是说你不喜欢我么?"}
    <class 'str'>

    除了可以对dict编码后以string的方式传递参数外,还可以直接使用json关键字直接传递

    import requests
    import json
    
    url='http://www.tuling123.com/openapi/api'
    
    json_data={"key":"4b6ce82fbe554a11b99dabfa3a4ae6d9","info":"beijing","userid":"jxn"}
    r=requests.post(url,json=json_data)
    print(r.text)

    结果:{"code":100000,"text":"北京"}
  • 相关阅读:
    打印java 对象信息的小技巧
    git 忽略已经跟踪文件的改动
    mysql主从备份方案
    Lucene4.3和Lucene3.5性能对比(二)
    Lucene4.3和Lucene3.5性能对比(一)
    Cracking the coding interview--Q1.1
    CRACKING THE CODING INTERVIEW 笔记(1)
    关于名称重整(name mangling)、多态性的一些简单介绍
    shell中sed用法
    GDB调试GCC(jRate)
  • 原文地址:https://www.cnblogs.com/tangqiu/p/7635896.html
Copyright © 2011-2022 走看看